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!

Pazu
  • 103

1 Answers1

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
Kusalananda
  • 333,661