bash中的字符串比较

时间:2014-11-24 00:19:43

标签: bash

我保证这是一个新手的错误,但我似乎无法让我的if-elif-else语句使用比较字符串。

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

3 个答案:

答案 0 :(得分:0)

要读入变量OS,而不是变量,其名称包含在变量OS中,请使用:

read OS

read $OS

顺便说一句 - 使用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标准),而不是{{ 1}}(这是一个bash扩展名)用于字符串相等。

答案 1 :(得分:0)

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

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

答案 2 :(得分: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