cgarrido
cgarrido

Reputation: 77

Shell Script To Only Run If $HOSTNAME Is Empty?

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

Upvotes: 0

Views: 1175

Answers (1)

Domin
Domin

Reputation: 1145

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

Upvotes: 2

Related Questions