2012-02-26 66 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