syntax error on if[“$foo” == “bar”] in bash

前端 未结 2 398
醉酒成梦
醉酒成梦 2020-12-12 04:51

I am new to bash, but according to some flow control guides I saw, this script should work just find, but I get line 4 syntax error near unexpected token then

相关标签:
2条回答
  • 2020-12-12 05:36

    In the shell, [ is a command and ] is an argument to that command. Arguments must be separate words, separated by white space. Aside from that, I would also suggest changing your == to = (the latter is more widely supported). Also, you can combine your echo and read statements using read -p.

    #!/bin/bash
    read -p $'Type your name\n' personname
    if [ "$personname" = "kevin" ]; then
        echo "Your name is kevin"
        exit 1
    fi
    

    The $'string\n' syntax allows you to use characters such as the newline \n in the prompt string. If you don't actually want a newline, you could simply use something like 'Type your name: ' and the prompt would appear on the same line as the user input.

    0 讨论(0)
  • 2020-12-12 05:42

    You are missing some spaces in if statement

    #!/bin/bash
    echo "Type your name"
    read personname
    if [ "$personname" == "kevin" ]; then
        echo "Your name is kevin"
        exit 1
    fi
    
    0 讨论(0)
提交回复
热议问题