Check existence of input argument in a Bash shell script

ID : 642

viewed : 114

Tags : bashshellbash

Top 5 Answer for Check existence of input argument in a Bash shell script

vote vote


It is:

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

The $# variable will tell you the number of input arguments the script was passed.

Or you can check if an argument is an empty string or not like:

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

The -z switch will test if the expansion of "$1" is a null string or not. If it is a null string then the body is executed.

vote vote


It is better to demonstrate this way

if [[ $# -eq 0 ]] ; then     echo 'some message'     exit 1 fi 

You normally need to exit if you have too few arguments.

vote vote


In some cases you need to check whether the user passed an argument to the script and if not, fall back to a default value. Like in the script below:

scale=${2:-1} emulator @$1 -scale $scale 

Here if the user hasn't passed scale as a 2nd parameter, I launch Android emulator with -scale 1 by default. ${varname:-word} is an expansion operator. There are other expansion operators as well:

  • ${varname:=word} which sets the undefined varname instead of returning the word value;
  • ${varname:?message} which either returns varname if it's defined and is not null or prints the message and aborts the script (like the first example);
  • ${varname:+word} which returns word only if varname is defined and is not null; returns null otherwise.
vote vote



 #!/bin/bash  if [ "$#" -eq  "0" ]    then      echo "No arguments supplied"  else      echo "Hello world"  fi 
vote vote


Another way to detect if arguments were passed to the script:

((!$#)) && echo No arguments supplied! 

Note that (( expr )) causes the expression to be evaluated as per rules of Shell Arithmetic.

In order to exit in the absence of any arguments, one can say:

((!$#)) && echo No arguments supplied! && exit 1 

Another (analogous) way to say the above would be:

let $# || echo No arguments supplied  let $# || { echo No arguments supplied; exit 1; }  # Exit if no arguments! 

help let says:

let: let arg [arg ...]

  Evaluate arithmetic expressions.    ...    Exit Status:   If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise. 

Top 3 video Explaining Check existence of input argument in a Bash shell script