2012-02-26 75 views
1

我似乎可以看到爲什麼這不起作用:Bash - IF [..] ||的麻煩結果[..]

#!/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 

當測試,看看它的工作原理:

[email protected]:~# testing.sh optionone optiontwo 
...Correct output... 
[email protected]:~# testing.sh optionone 
usage: testing.sh <username> 

回答

2

需要注意的是EXE在cuting 2個命令:

[ $# -ne 1 ] || [ $# -ne 2 ] 

[ $# -ne 1 ]是一個第一命令,並且僅當先前的具有非零的錯誤代碼作爲||殼操作者執行[ $# -ne 2 ]命令。

對你來說,這並不重要,但是在波紋管的情況下,它是:

[ $? -eq 0 ] || [ $? -eq 1 ] 

的第二命令將永遠是真實的,作爲第二$?[ $? -eq 0 ]返回代碼。你可以用波紋管,該行測試,將打印true兩次:

function f() { return $1; } 
f 1 
{ [ $? -eq 0 ] || [ $? -eq 1 ]; } && echo "true" 
f 2 
{ [ $? -eq 0 ] || [ $? -eq 1 ]; } && echo "true" 

正確的方式在一個命令執行or是:

[ $? -eq 0 -o $? -eq 1 ] 

這樣一來,這些波紋管只打印true一次:

function f() { return $1; } 
f 1 
{ [ $? -eq 0 -o $? -eq 1 ]; } && echo "true" 
f 2 
{ [ $? -eq 0 -o $? -eq 1 ]; } && echo "true" 

關於你原來的問題,kev已經指出你的tes有一個邏輯錯誤噸。的[ $# -eq 1 ] || [ $# -eq 2 ]負是NOT [ $# -eq 1 ] && NOT [ $# -eq 2 ]這成爲[ $# -ne 1 ] && [ $# -ne 2 ]或者一個命令:

[ $# -ne 1 -a $# -ne 2 ] 
0

一種方法,使這項工作轉出-ne比較運算符爲-lt-gt小於大於)爲條件語句。就像這樣:

#!/bin/bash 

#Should run if there are either 1 or 2 options specified 
if [ $# -lt 1 ] || [ $# -gt 2 ]; then 
    echo "usage: ${0##*/} <username>" 
    exit 
fi 
+0

忽略了最低在所有的工作與代碼.. '根@ Ubuntu的:〜#testing.sh你好再見 用法: testing.sh root @ ubuntu:〜#testing.sh hello usage:testing.sh ' – King 2012-02-26 02:16:32

+0

我修復了答案;它現在應該爲你工作? – summea 2012-02-26 03:02:05

+0

我導致只使用'if [$ {1}]然後echo「」else ... exit ...' – King 2012-02-26 04:46:44

5

更改布爾邏輯:

if [ $# -ne 1 ] && [ $# -ne 2 ]; then 

或者

if ! ([ $# -eq 1 ] || [ $# -eq 2 ]); then 

順便說一句,你可以使用Shell-Arithmetic((...))

if (($#!=1 && $#!=2)); then 
+0

如果2是真的,那麼1返回假,反之亦然,所以它必須是或 – King 2012-02-26 04:48:27

+0

請注意,使用圓括號,你正在開始一個子殼。這個函數f(){a = hello; ! (a = world && {[$#-eq 1] || [$#-eq 2];})&& echo $ a; }; f a b c'將打印'hello'和這個'函數f(){a = hello; ! {a = world && {[$#-eq 1] || [$#-eq 2]; }} && echo $ a; }; f a b c'將打印「世界」。 – jfg956 2012-02-26 09:31:48

+0

@King請僅僅試試/測試'&&'的東西。 – 2012-02-26 09:38:41