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
  • 2
  • 1
    have you tried surrounding bracket with space ? `["$ANSWER"` ==> `[ "$ANSWER"` – Archemar May 05 '19 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?](https://unix.stackexchange.com/questions/117438/why-are-bash-tests-so-picky-about-whitespace). – fra-san May 05 '19 at 11:35

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
  • 320,670
  • 36
  • 633
  • 936
  • One last question: why do you use 'printf' instead of 'echo'? – Pazu May 05 '19 at 16:02
  • @Pazu Oh, I use `printf` whenever I output non-constant data. See e.g. [Why is printf better than echo?](//unix.stackexchange.com/q/65803) – Kusalananda May 05 '19 at 16:24