echo $HOST
on my laptop correctly shows Nbook
as the hostname. But the simple shell script below always executes the first echo
command regardless of the hostname I supply in the if
condition above it. It seems I am missing something simple. Any help is appreciated. Thanks!
#!/bin/sh
if [ $HOST="whatever!" ]; then
echo "This is Nbook" # always executes!
elif [ $HOST="PC" ]; then
echo "This is PC"
else
echo "Unknown host"
fi
EDIT: The modified code below, now with whitespaces around =
in the if
condition, still does not give the expected result. I should now get This is Nbook
, but it executes the last echo
command Unknown host
instead. My understanding from the answers here is that "$HOST" = "Nbook"
should be interpreted as three separate arguments to the test function, in which case =
is the intended operator and should return true
. Looks like I am again missing something.
#!/bin/sh
if [ "$HOST" = "Nbook" ]; then
echo "This is Nbook"
elif [ "$HOST" = "PC" ]; then
echo "This is PC"
else
echo "Unknown host"
fi
UPDATE: Thanks to Charles Duffy's help in the comments below, the following code works (I replaced $HOST
by $(hostname)
:
#!/bin/sh
host=$(hostname)
if [ "$host" = "Nbook" ]; then
echo "This is Nbook"
elif [ "$host" = "PC" ]; then
echo "This is PC"
else
echo "Unknown host"
fi