Monday, January 31, 2022

[SOLVED] if statement to check $HOSTNAME in shell script

Issue

So I want to set some paths differently depending on the host, but unfortunately it's not working. Here is my script:

if [$HOSTNAME == "foo"]; then
    echo "success"
else
    echo "failure"
fi

This is what happens:

-bash: [foo: command not found
failure

I know for certain that $HOSTNAME is foo, so I'm not sure what the problem is. I am pretty new to bash though. Any help would be appreciated! Thanks!


Solution

The POSIX and portable way to compare strings in the shell is

if [ "$HOSTNAME" = foo ]; then
    printf '%s\n' "on the right host"
else
    printf '%s\n' "uh-oh, not on foo"
fi

A case statement may be more flexible, though:

case $HOSTNAME in
  (foo) echo "Woohoo, we're on foo!";;
  (bar) echo "Oops, bar? Are you kidding?";;
  (*)   echo "How did I get in the middle of nowhere?";;
esac


Answered By - Jens
Answer Checked By - Marilyn (WPSolving Volunteer)