Home > Software engineering >  script if variable empty not execute command, if variable available execute
script if variable empty not execute command, if variable available execute

Time:12-27

I am writing a script to disable the puppet agent. I would like to implement this logic:

  • if reason variable null or empty, halt with an explanatory message;
  • else execute the disabling command (puppet agent --disable "$reason")

How can I write the if condition in the execute() function in the below script to achieve that?

#!/bin/bash

set -e

lockfile='/opt/puppetlabs/puppet/cache/state/agent_disabled.lock'
reason='who:until:why'

execute () {
    if [[ -z $reason && ${reason x} ]]; then
      echo "Disabling reason is not set"
    fi
}

puppet agent --disable "$reason"


# Verify if the Agent is Disabled or not
if [ -f "$lockfile" ]; then
  echo 'puppet agent is disabled'
fi

CodePudding user response:

Assuming my clarifying edit to the question to have adequately captured the intent, we have

  • if reason variable null or empty, halt with an explanatory message;

Bash's -z conditional operator can catch both null and empty cases, including when the value is null on account of the variable not being set at all, but remember that it is evaluated after the command is fully expanded. Possibly, then, this is the test you want to perform:

if [[ -z "$reason" ]]; then # ...
  • else execute the disabling command (puppet agent --disable "$reason")

Your example code executes that command unconditionally. I guess you instead want to put it in an else block of the condition, or otherwise perform it only in the event that the previous condition is not satisfied.

I don't really see any gain from using a function here. I would probably implement what I think you are describing like this:

#!/bin/bash

lockfile='/opt/puppetlabs/puppet/cache/state/agent_disabled.lock'
reason='who:until:why'

if [[ -z "$reason" ]]; then
  echo "Disabling reason is not set"  1>&2
else
  puppet agent --disable "$reason"

  # Verify that the agent is disabled
  if [ -f "$lockfile" ]; then
    echo 'puppet agent is disabled'  1>&2
  fi
fi

Alternatively, I don't see how the disablement reason could ever fail to meet the criterion in the code presented, so maybe you mean to write a wrapper function that takes the reason as an argument:

disable_puppet() {
  local reason=$1

  if [[ -z "$reason" ]]; then
    echo "Disabling reason is not set" 1>&2
  else
    puppet agent --disable "$reason"

    # Verify that the agent is disabled
    if [ -f "$lockfile" ]; then
      echo 'puppet agent is disabled' 1>&2
    fi
  fi
}
  • Related