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?
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.
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.
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.
$1 is the first argument (filename1) $2 is the second argument (dir1) $9 is the ninth argument.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With