简体   繁体   中英

linux shell script variable “not found”

Just trying to exit a loop once no input is entered at the prompt, but I'm having trouble testing for the value in an if statement?

CODE:

SQL="?";
while true 
do

    if [ "$SQL" == "" ]
    then
        break
    else    
        read -p "SQL: "  SQL
        clear
        php -f sql.php "$SQL"
    fi
    
done

OUTPUT:

sql.sh: 5: [: ?: unexpected operator
SQL: 

Although it looks like part of a scripting language, [ is actually the name of a command, also known as test . The if statement runs that command, and acts based on its result. (The same is true, incidentally, of the true in your while loop - it's a command that "does nothing, successfully".)

As such, you need a space between the command and its parameters, as well as between the if and the command. You also need to use the correct arguments; the standard spelling for comparing two strings is = rather than ==

if [ "$SQL" = "" ]

Which is equivalent to:

if test "$SQL" = ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM