0

I'm trying to write a shell script that ONLY runs if $HOSTNAME is empty (for example on a node that has zeroized). However, even when the host-name has already been set the if condition of my code keeps running. Have I missed something?

$HOSTNAME=$(hostname)
if [ "$HOSTNAME" = "" ]; then
    logger "STARTING sleep 120s to complete boot process"
    sleep 120
    logger "AFTER 120s"
    logger "STARTING configuration using script"
    /usr/sbin/cli -c '
    configure;
    #Configuration changes happen here
    commit'
else
    echo "No changes were made"
fi
5
  • 1
    How are you setting HOSTNAME? (Or maybe more relevantly, how are you preventing HOSTNAME from being set, depending on what shell you are using?) Commented Nov 14, 2019 at 19:58
  • @chepner i've tried using $HOSTNAME = $(hostname). The hope was that if it is empty then the "if" statement runs and makes a configuration change on the node. Otherwise nothing should happen. Commented Nov 14, 2019 at 20:03
  • 1
    It should be HOSTNAME=$(hostname) (no $ before HOSTNAME, no spaces around the =). If you are using bash, HOSTNAME is already set. Commented Nov 14, 2019 at 20:05
  • Thank you so much! I thought variables ALWAYS had to have the $. Commented Nov 14, 2019 at 20:29
  • 1
    Not in shell (unlike Perl and, I think, PHP); a $ prefixed to a parameter name signals a parameter expansion. Commented Nov 14, 2019 at 20:32

1 Answer 1

2

Firstly, to assign a variable in bash you don't need to use a dollar $.
Secondly, to check condition in an if statement you must use == instead of =.
And finally, it's better to check length of the string, instead of comparing to "". You can do it by using -z option.
Here's fixed code:

#!/bin/bash
HOSTNAME=$(hostname)
if [ -z "$HOSTNAME" ]; then
    logger "STARTING sleep 120s to complete boot process"
    sleep 120
    logger "AFTER 120s"
    logger "STARTING configuration using script"
    /usr/sbin/cli -c '
    configure;
    #Configuration changes happen here
    commit'
else
    echo "No changes were made"
fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.