Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that a parameter was supplied to a bash script [duplicate]

Tags:

bash

I just want to check if one parameter was supplied in my bash script or not.

I found this, but all the solutions seem to be unnecessarily complicated.

What's a simple solution to this simple problem that would make sense to a beginner?

like image 579
node ninja Avatar asked Jan 23 '12 08:01

node ninja


People also ask

How do you check parameters in bash?

Get Values of All the Arguments in Bash We can use the $* or the $@ command to see all values given as arguments. This code prints all the values given as arguments to the screen with both commands.

What is == in bash script?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.

What does $@ mean in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does $2 mean in a bash shell script?

$1 is the first argument (filename1) $2 is the second argument (dir1) $9 is the ninth argument.


1 Answers

Use $# which is equal to the number of arguments supplied, e.g.:

if [ "$#" -ne 1 ] then   echo "Usage: ..."   exit 1 fi 

Word of caution: Note that inside a function this will equal the number of arguments supplied to the function rather than the script.

EDIT: As pointed out by SiegeX in bash you can also use arithmetic expressions in (( ... )). This can be used like this:

if (( $# != 1 )) then   echo "Usage: ..."   exit 1 fi 
like image 142
Adam Zalcman Avatar answered Oct 08 '22 10:10

Adam Zalcman