学习Bash条件 - 语法错误

时间:2018-02-07 02:20:33

标签: linux bash shell if-statement

好。我一直在敲打Linux墙。我在这里做错了什么:

#! /bin/bash
echo
echo "1. Windows (Microsoft)
echo  2. Linux (Red Hat)
echo  3. MacOS (Apple)
echo
echo -n Select your OS choice [1, 2 or 3]: "
READ OS
echo

if [ "$OS" -eq 1 ]; then
echo "You picked Windows (Microsoft)."
fi
if [ "$OS" -eq 2 ]; 
echo "You picked Linux (Red Hat)."
fi
if [ "$OS" -eq 3 ]; then
echo "You picked MacOS (Apple)."
fi
if [ "$OS" > 3 || "$OS" < 1 ]];
echo "Invalid selection!"
fi
exit 1

错误消息

[ : : integer expression expected

1 个答案:

答案 0 :(得分:0)

您使用了错误的if / elif / else语法:

if [ "$OS" -eq 1 ] 
then
    echo "You picked Windows (Microsoft)."
elif [ "$OS" -eq 2 ] 
then 
     echo "You picked Linux (Red Hat)."
elif [ "$OS" -eq 3 ] 
then
     echo "You picked MacOS (Apple)."
else 
     echo "Invalid selection!"
fi
exit 1

此外,如果您想使用更大或更低级,您应该使用-gt-lt等。 请参阅此页面:http://tldp.org/LDP/abs/html/comparison-ops.html

还可以在此链接查看orand的语法:http://tldp.org/LDP/abs/html/ops.html#ANDOR

此外,我刚发现它应该具有与结束方括号相同的开口方括号。

修复脚本中的所有问题后:

#! /bin/bash

echo
echo "1. Windows (Microsoft)"
echo "2. Linux (Red Hat)"
echo "3. MacOS (Apple)"
echo
echo -n "Select your OS choice [1, 2 or 3]: "
read OS
echo

if [ "$OS" -eq 1 ] 
then
    echo "You picked Windows (Microsoft)."
elif [ "$OS" -eq 2 ] 
then 
     echo "You picked Linux (Red Hat)."
elif [ "$OS" -eq 3 ] 
then
     echo "You picked MacOS (Apple)."
else 
     echo "Invalid selection!"
fi
exit 0

执行时生成以下输出:

arobert@arobert-VirtualBox [11:48:52]
[/home/arobert/test_awk] >
./ostype.sh 

1. Windows (Microsoft)
2. Linux (Red Hat)
3. MacOS (Apple)

Select your OS choice [1, 2 or 3]: 2

You picked Linux (Red Hat).
arobert@arobert-VirtualBox [11:48:56]
[/home/arobert/test_awk] >
./ostype.sh 

1. Windows (Microsoft)
2. Linux (Red Hat)
3. MacOS (Apple)

Select your OS choice [1, 2 or 3]: 1

You picked Windows (Microsoft).
arobert@arobert-VirtualBox [11:49:00]
[/home/arobert/test_awk] >
./ostype.sh 

1. Windows (Microsoft)
2. Linux (Red Hat)
3. MacOS (Apple)

Select your OS choice [1, 2 or 3]: 3 

You picked MacOS (Apple).
arobert@arobert-VirtualBox [11:49:05]
[/home/arobert/test_awk] >
./ostype.sh 

1. Windows (Microsoft)
2. Linux (Red Hat)
3. MacOS (Apple)

Select your OS choice [1, 2 or 3]: 5

Invalid selection!