[英]Error in if else statement in linux shell script
Being newbie in linux shell scripting, I had tried to implement the following code in test.sh
: 作为linux shell脚本的新手,我试图在
test.sh
实现以下代码:
#!/bin/sh
# This is some secure program that uses security.
clear
VALID_PASSWORD="secret" #this is our password.
echo "Please enter the password:"
read PASSWORD
if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
echo "You have access!";
else
echo "ACCESS DENIED!";
fi
But while executing the script, it shows me following error: 但是在执行脚本时,它显示了以下错误:
Please enter the password:
1234
./tst1.sh: 9: [: 1234: unexpected operator
ACCESS DENIED!
I am unable to debug this error. 我无法调试此错误。 Appreciate the much needed help.
感谢急需的帮助。
If you are using Shell, you need to use the POSIX comparison =
. 如果使用的是Shell,则需要使用POSIX比较
=
。
That is, use: 也就是说,使用:
if [ "$PASSWORD" = "$VALID_PASSWORD" ]; then
# ^
Instead of 代替
if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
# ^^
You can have a good read to What is the difference between test, [ and [[ ? 您可以很好地了解test,[和[[有什么区别? in order to see all the variances.
为了查看所有差异。 Basically, if you are in Shell, use the POSIX tiny set of possibilities;
基本上,如果您在Shell中,请使用POSIX极小的可能性; if you are in Bash, you can use other things such as
[[
: 如果您在Bash中,则可以使用
[[
:
| new test [[ | old test [
----------------------------------------------
| > | \>
string | < | \<
comparison | = (or ==) | =
| != | !=
Correct Syntax for If - Else in Linux is below If的正确语法-Linux中的Else如下
if [ "$1" = "cool" ]
then
echo "Cool Beans"
else
echo "Not Cool Beans"
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.