Bash - IF [..] ||令人烦恼的结果 [..]

Mr.*_*ing 1 bash if-statement

我似乎可以看出为什么这不起作用:

#!/bin/bash

if [ $# -ne 1 ] || [ $# -ne 2 ]; then 
# Should run if there are either 1 or 2 options specified
  echo "usage: ${0##*/} <username>"
  exit
fi
Run Code Online (Sandbox Code Playgroud)

在测试时是否有效:

root@ubuntu:~# testing.sh optionone optiontwo
...Correct output...
root@ubuntu:~# testing.sh optionone
usage: testing.sh <username>
Run Code Online (Sandbox Code Playgroud)

kev*_*kev 5

更改布尔逻辑:

if [ $# -ne 1 ] && [ $# -ne 2 ]; then
Run Code Online (Sandbox Code Playgroud)

要么

if ! ( [ $# -eq 1 ] || [ $# -eq 2 ] ); then
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你可以使用Shell-Arithmetic ((...)):

if (( $#!=1 && $#!=2 )); then
Run Code Online (Sandbox Code Playgroud)