2014-11-24 81 views
0

我保证这是一个新手的错误,但我似乎无法让我的if-elif-else语句与比较字符串一起工作。在bash中的字符串比较

echo "What is your current OS?" 
read $OS 
if [ "$OS" == "Unix" ] 
then  
    echo "Unix is pretty good.." 
elif [ "$OS" == "Linux" ] 
then  
    echo "Open-source eh?" 
elif [ "$OS" == "Windows" ] 
then  
    echo "Microsoft owns the universe" 
elif [ "$OS" == "OSX" ] 
then  
    echo "Apple has control over you" 
else  
    echo "Not a valid os type." 
fi 
+2

首先使用'=',而不是'==',以符合POSIX标准。第二 - '读取操作系统',而不是'读取操作系统' – 2014-11-24 00:22:45

+0

其他答案可能看起来不像基于其标题的重复 - 但底层问题是相同的。 – 2014-11-24 00:29:46

回答

0

您正在阅读$OS,这是OS变量的值。

您想要读取OS,然后使用sigil来访问它:$OS

0

要读入变量OS,不进变量其名称包含在变量OS,用途:

read OS 

read $OS 

通过方式 - 这个代码将会更好tten与case声明:

case $OS in 
    Unix) echo "Unix is pretty good.." ;; 
    Linux) echo "Open-source eh?" ;; 
    Windows) echo "Microsoft owns the universe" ;; 
    OSX) echo "Apple has control over you" ;; 
    *) echo "Not a valid os type." ;; 
esac 

相反,如果你要使用test(又名[),使用=(这是符合POSIX标准),而不是==(这是一个bash扩展)为字符串相等。

0
if [ "$#" != 1 ] 
then 
    echo $0 OS 
    exit 
fi 
case "$1" in 
Unix) echo 'Unix is pretty good..'  ;; 
Linux) echo 'Open-source eh?'    ;; 
Windows) echo 'Microsoft owns the universe' ;; 
OSX)  echo 'Apple has control over you' ;; 
*)  echo 'Not a valid os type.'  ;; 
esac 
+0

使用命令行参数而不是从标准输入读取是一个非常大的行为变化,无需评论。 – 2014-11-24 00:27:05