Quantcast
Channel: How to determine if a bash variable is empty? - Server Fault
Viewing all articles
Browse latest Browse all 16

Answer by mgutt for How to determine if a bash variable is empty?

$
0
0

I prefer the way how PHP checks for an empty variable as Luca mentioned in his answer, too. But instead of using a separate function, I use a "filter" which finally allows using usual bash conditions.

Imagine you have a bash script with a settings section like this:

# enable test modedry_run=false# overwrite files if they already existoverwrite_files=true

The users of the script should be able to set it as they like:

dry_run=dry_run=""dry_run=0dry_run="0"dry_run=falsedry_run="false"# or delete it completely

So in the script section itself I do this:

# check user settings[[ $dry_run == 0 ]] || [[ $dry_run == false ]] && unset dry_run[[ $overwrite_files == 0 ]] || [[ $overwrite_files == false ]] && unset overwrite_files

Now, I can be sure that the variable exists with a content or not, so I can use a usual condition like this:

if [[ $dry_run ]]; then  echo "dry run is true"else  echo "dry run is false"fi

PS I skipped filtering "0.0" as I don't think a user would disable a setting by setting this, but feel free to extend the filter if you need it.


Viewing all articles
Browse latest Browse all 16

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>