bash - 用于退出带有错误消息的 bash 脚本的更好的一行代码

标签 bash

我想用一个更干净、不那么丑陋的单行代码来完成测试:

#!/bin/bash
test -d "$1" || (echo "Argument 1: '$1' is not a directory" 1>&2 ; exit 1) || exit 1

# ... script continues if $1 is directory...

基本上我追求的是不重复 exit 的东西,并且最好不产生子 shell(因此看起来也不那么难看),但仍然适合一行。

最佳答案

没有子 shell 也没有复制 exit:

test -d "$1" || { echo "Argument 1: '$1' is not a directory" 1>&2 ; exit 1; }

您可能还想引用 Grouping Commands :

{}

{ list; }

Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.

关于bash - 用于退出带有错误消息的 bash 脚本的更好的一行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19515246/

相关文章:

PHPUnit - Bash 脚本输出到变量

node.js - Docker仅在构建后运行

bash - 了解bash信号处理

linux - 在 bash 脚本中比较两个文件时没有这样的文件或目录错误

bash - 在 shell 命令之后通过管道传递 vim 命令

linux - 下面的 awk 有什么问题

python - 从 Bash 导入 Python 模块

string - 更改索引 X 处的字符串 char

bash - 为什么 sudo pm-suspend 在 i3 平铺窗口管理器中不起作用?

bash - 引导新的 EC2 实例时使用 UserData 中的内部函数