gpt4 book ai didi

linux - 学习 Bash 条件 - 语法错误

转载 作者:太空宇宙 更新时间:2023-11-04 12:11:47 25 4
gpt4 key购买 nike

好的。我一直在用头撞 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

最佳答案

你使用了错误的 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!

关于linux - 学习 Bash 条件 - 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48654966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com