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…

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:

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, and you run Devsrealm, you would get the following:

user@server:~/bin$ Devsrealm
Hello Devsrealm

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

Comment policy: Respectful and beneficial comments are welcome with full open hands. However, all comments are manually moderated and those that doesn't relate with what the passage is saying or offensive comments would be deleted. Thanks for understanding!

Leave a Reply

Your email address will not be published. Required fields are marked *