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
["$ANSWER"
==>[ "$ANSWER"
– Archemar May 05 '19 at 10:51["$ANSWER" == "root"]
compound list afterif
should also give you a "command not found" error (unless you have in yourPATH
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 05 '19 at 11:35