check if input arguments exists in shell script

How to Check if Input Argument Exists in Shell Script

Shell scripts are great to automate tasks in Linux systems. They also allow you to send input arguments that you can process further within the script. But if you refer to an input argument that does not exist then you will get an error while running your shell script. So it is advisable to check if input argument exists in shell script before we process them. Here are the steps to do it.


How to Check if Input Argument Exists in Shell Script

There are a couple of ways to check if input arguments exists in shell script.


1. Check if No Arguments are Supplied

The $# shell variable stores the number of input variables supplied to shell script. We can use this to determine if any variable was supplied to your shell script. Here is an example to do so.

if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
fi


2. Check if Specific Argument exists

You can also check if a specific argument exists on not. The first argument supplied to a shell script is stored in $1, the second argument in $2, and so on.

You can use -z operator to check if a specific shell variable is empty or not. Here is an example to check if the first argument exists or not.

if [ -z "$1" ]
  then
    echo "No argument supplied"
fi

Similarly, you can also check if a shell variable does not exist, by adding negation operator before -z operator, as shown below.

if [ ! -z "$1" ]
  then
    echo "1st argument supplied"
fi

In this article, we have seen a couple of simple ways to easily check if input arguments exist or not. It is always a best practice to check if an input argument exists before you use it, to avoid unnecessary error messages and prevent your script from stopping. You can use these snippets in any part of your shell script. They work fine on all shells across all Linux distributions.

Also read:

How to Check if Variable is Empty or Not
How to Check if File Exists in Shell Script
How to Check if Directory Exists in Shell Script
How to Check if Directory Exists in Python
How to Get Directory of Shell Script

Leave a Reply

Your email address will not be published.