0
read -p "What is your name?:" ANSWER
if ["$ANSWER" == "root"]
    then
        echo "Hello, administrator"
    else
        echo "Hello, $ANSWER" 
fi

If I answer "root" in the console, I assumed to get "Hello, administrator" out of it but I always get the second case. What am I doing wrong? [I also tried different if-conditions such as "$ANSWER" = "myname" and it still didn't work]. Thanks in advance!

  • 1
    have you tried surrounding bracket with space ? ["$ANSWER" ==> [ "$ANSWER" – Archemar May 5 at 10:51
  • 1
    The ["$ANSWER" == "root"] compound list after if should also give you a "command not found" error (unless you have in your PATH an executable file named as [ + the expansion of $ANSWER). Doesn't it? About spaces in shell tests, see, for instance, Why are bash tests so picky about whitespace?. – fra-san May 5 at 11:35
3

Your code has syntactic issues. There must be a space after [ and in front of ] in the test:

read -p "What is your name?:" ANSWER

if [ "$ANSWER" == "root" ]; then
    echo 'Hello, administrator'
else
    printf 'Hello, %s\n' "$ANSWER"
fi

Additionally, you may want to use the id utility to get the UID of the user. The root user always has a UID of zero:

if [ "$(id -u)" -eq 0 ]; then
    echo 'Hello, administrator'
else
    printf 'Hello, %s\n' "$(id -u -n)"
fi

id -u will return the UID of the current user as a positive integer while id -u -n will return the username. You could also use $USER or $LOGNAME to print the username, but it's safer to use the UID (number) in comparisons.

The bash shell also stores the UID of the current user in $UID, so in bash, you could write

if [ "$UID" -eq 0 ]; then
    echo 'Hello, administrator'
else
    printf 'Hello, %s\n' "$USER"
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.