linux shell脚本中if else语句出错

时间:2016-05-06 06:20:26

标签: linux shell

作为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

但是在执行脚本时,它会显示以下错误:

Please enter the password:
1234
./tst1.sh: 9: [: 1234: unexpected operator
ACCESS DENIED!

我无法调试此错误。欣赏急需的帮助。

3 个答案:

答案 0 :(得分:3)

如果您使用的是Shell,则需要使用POSIX比较=

即,使用:

if [ "$PASSWORD" = "$VALID_PASSWORD" ]; then
#                ^

而不是

if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
#                ^^

您可以很好地阅读What is the difference between test, [ and [[ ?以查看所有差异。基本上,如果你在Shell中,请使用POSIX微小的可能性;如果您使用Bash,则可以使用其他内容,例如[[

            |   new test [[   |   old test [
----------------------------------------------
            |      >          |      \>
string      |      <          |      \<
comparison  |   = (or ==)     |      =
            |      !=         |      !=

答案 1 :(得分:2)

用于比较两个字符串的比较运算符RestSharp.RestClient ClientNonce = new RestSharp.RestClient("https://connect.squareup.com"); RestSharp.RestRequest RequestNonce = new RestSharp.RestRequest("v2/card_nonce", RestSharp.Method.POST); RequestNonce.RequestFormat = RestSharp.DataFormat.Json; RequestNonce.AddHeader("Accept", "application/json"); string jsonBodyNone = "{\"client_id\":\""+sandboxId+"\",\"card_data\":{\"billing_postal_code\":\"73001\",\"cvv\":\"564\",\"exp_month\":\"1\",\"exp_year\":\"2021\",\"number\":\"4532759734545858\"},\"website_url\":\"http://localhost:24584/\"}"; RequestNonce.AddParameter("application/json", jsonBodyNone, RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse responseNonce = ClientNonce.Execute(RequestNonce); System.Net.HttpStatusCode getresponseNonce = responseNonce.StatusCode; Bash扩展名,它在基本==中不存在,它使用test命令它使用单个 sh来比较字符串。

答案 2 :(得分:1)

在Linux中使用If - Else的正确语法

if [ "$1" = "cool" ]
then
    echo "Cool Beans"
else
    echo "Not Cool Beans"
fi