在bash中使用内联if语句添加命令参数
仅当变量的计算结果为某个值时,我才想在bash中的命令中添加参数。例如,这项工作:在bash中使用内联if语句添加命令参数,bash,Bash,仅当变量的计算结果为某个值时,我才想在bash中的命令中添加参数。例如,这项工作: test=1 if [ "${test}" == 1 ]; then ls -la -R else ls -R fi 这种方法的问题是,当test为1或是其他内容时,我必须复制ls-R。我更希望我能在一行中编写,而不是像这样(不起作用的伪代码): 我尝试了以下方法,但无效: ls (if ${test} == 1 then -la) -R test=1 ls `if [ $test -e
test=1
if [ "${test}" == 1 ]; then
ls -la -R
else
ls -R
fi
这种方法的问题是,当test
为1
或是其他内容时,我必须复制ls-R
。我更希望我能在一行中编写,而不是像这样(不起作用的伪代码):
我尝试了以下方法,但无效:
ls (if ${test} == 1 then -la) -R
test=1
ls `if [ $test -eq 1 ]; then -la; fi` -R
这给了我以下错误:
./test.sh: line 3: -la: command not found
使用
echo
打印参数:
test=1
ls `if [ $test -eq 1 ]; then echo "-la"; fi` -R
不使用
eval
和BASH数组的另一个答案:
myls() { local arr=(ls); [[ $1 -eq 1 ]] && arr+=(-la); arr+=(-R); "${arr[@]}"; }
将其用作:
myls
myls "$test"
此脚本在数组中构建整个命令
arr
,并保留命令选项的原始顺序。更惯用的版本:
由于echo
本身了解一些选项,因此使用printf%s
更安全,以确保要打印的文本不会被误认为是选项。请注意,此处不能引用命令替换-这在本例中是很好的,但通常需要更健壮的方法-请参见下文 但是,一般来说,更健壮的方法是在数组中建立参数,并将其作为一个整体传递:
# Build up array of arguments...
args=()
(( test == 1 )) && args+=( '-la' )
args+=( '-R' )
# ... and pass it to `ls`.
ls "${args[@]}"
更新:OP询问如何有条件地添加一个额外的、基于变量的参数,以生成ls-R-la“$PWD”
。
在这种情况下,数组方法是必须的:每个参数必须成为自己的数组元素,这对于支持可能嵌入空格的参数至关重要:
(( test == 1 )) && args+= ( '-la' "$PWD" ) # Add each argument as its own array element.
至于为什么你的命令
ls `if [ $test -eq 1 ]; then -la; fi` -R
不起作用:
在backticks(或其现代的、可嵌套的等价物,$(…)
)之间执行一个命令,即所谓的命令,它的执行方式与任何其他shell命令(尽管是在一个子shell中)一样,并且整个构造将替换为该命令的stdout输出
因此,您的命令尝试执行字符串-la
,但失败。要将其发送到stdout,您必须使用echo
或printf
等命令,使用[“$ENV_VARIABLE”==“true”]]和&args+=('-la')
您可以使用环境变量有条件地检查其值。
ls `if [ $test -eq 1 ]; then -la; fi` -R