Jonathan Viana
Jonathan Viana

Reputation: 103

Bash Execute code if a variable is not empty

I hope you're having a great weekend,

I'm trying to create a script that execute a for only if a variable is not empty and if the variable is empty execute the command just one time, something like the following:

#!/bin/bash
X=$1
function execute
{
if [ ! -z $X ]
then
  $*
fi
}
execute for count in 1 2 3 4
execute do
  execute echo $count
  echo $(hostname)
execute done

Upvotes: 0

Views: 1429

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84333

Quote Marks are Your Friends

You need to quote your variables, and you should also use the Bash test construct unless portability is an issue. There may be other problems with your code, but this refactoring should solve the problem you're specifically asking about.

#!/bin/bash

x="$1"

execute () {
    if [[ -n "$x" ]]; then
      "$@"
    fi
}

for count in {1..4}; do
  execute echo "$count"
  echo $(hostname)
done

Depending on your hostname, this will output something similar to:

1
localhost.local
2
localhost.local
3
localhost.local
4
localhost.local

Upvotes: 1

Related Questions