在bash中使用内联if语句添加命令参数
只有当变量求值为某个值时,我才想在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 -eq 1 ]; then -la; fi` -R 这给了我以下错误: ./test.sh: line 3: -la: command not found
一个更惯用的版本
svlasov’s answer:
ls $( (( test == 1 )) && printf %s '-la' ) -R 由于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 不起作用: 反引号(或其现代的,可嵌套的等价物,$(…))之间的命令 – 一个所谓的command substitution – 就像任何其他shell命令一样执行(虽然在子shell中)并且整个构造被替换为命令的stdout输出. 因此,您的命令尝试执行字符串-la,该字符串失败.要将其发送到stdout,这里需要使用echo或printf等命令. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |