media file explorer download upload index folder image licenses menu widget Play Pause profile-settings more dots-two-horizontal dots-two-vertical more-vertical pending google-plus hangouts facebook instagram whatsapp spotify telegram twitter vine renren rss youtube twitch vimeo flickr dribble behance deviantart 500px steam github soundcloud skype reddit linkedin lastfm delicious stackoverflow pinterest xing flattr foursquare yelp World

Check If Variable Is Not Empty [isset] (Bash)

In the getting started with bash guide, we took a sneak peek in customizing script with argument, the issue with the example is that we aren't checking if the variable is set or not before returning the output, which we are going to amend in this guide.

We would ensure that a value has been supplied to the first positional parameter.

Take for example...

#!/bin/bash
echo "Hello $1"
exit 0

If you run the following script, it would output Hello, and if you pass a first positional parameter, it would output "Hello" with whatever parameter you pass to the variable.

But we can do better by first checking if the value we expected has been supplied, if it is, then we echo the result, if not, we skip the hello statement entirely. This is the modified version:

#!/bin/bash
test -z $1 || echo "Hello $1"
exit 0

The test statement is used for file comparison, it returns a status of 0 (true) or 1 (false) depending on the evaluation of the conditional expression EXPR. Each part of the expression must be a separate argument.

So, test -z $1 would check if the $1 is empty, and if it is, you won't get any output, if otherwise, we would see the hello message with the string we supply.

If you store the name of the script isset.sh, and you run isset.sh Devsrealm, you would get the following:

user@server:~/bin$ isset.sh Devsrealm
Hello Devsrealm

In the coming guide, we would take a closer look at the test shell builtin command.