![如何使用嵌套 [] 替换 if-then-fi ? (“[:-f:预期二元运算符”)](https://linux22.com/image/53395/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E5%B5%8C%E5%A5%97%20%5B%5D%20%E6%9B%BF%E6%8D%A2%20if-then-fi%20%EF%BC%9F%20%EF%BC%88%E2%80%9C%5B%EF%BC%9A-f%EF%BC%9A%E9%A2%84%E6%9C%9F%E4%BA%8C%E5%85%83%E8%BF%90%E7%AE%97%E7%AC%A6%E2%80%9D%EF%BC%89.png)
在我的 .bashrc 文件中,我有:
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then . /etc/bash_completion; fi
我想用[]
它来代替if then fi
我已经有了
[ -f ~/.bash_aliases ] && source ~/.bash_aliases
[ "${BASH_VERSINFO[0]}" -ge 4 ] && shopt -s autocd
[ -f ~/.git-completion.bash ] && source ~/.git-completion.bash
所以我想也许我可以用
[ [ -f /etc/bash_completion ] && [! shopt -oq posix] ] && . /etc/bash_completion
但我得到
-bash: [: -f: binary operator expected
答案1
你可以直接连锁&&
,不需要巢这里的条件:
[ -f /etc/bash_completion ] && ! shopt -oq posix && . /etc/bash_completion
作品。
答案2
您混淆了两个命令。[
不等于if
.[
相当于test
.
if
甚至不是一个简单的命令,而是一个保留字(如[[
),控制结构的一部分。if ... then ... else ... fi
几乎等于... && { ...; true; } || { ... }