Dimitar Slavchev
Dimitar Slavchev

Reputation: 1667

How to make check on args in bash and execute some command if a sertain argument was not set?

I know how to give default values to arguments in bash or exit with an error message if one is unset. (from here)

I want to make check if an argument was set, execute some code if it wasn't and the exit.

if [$1 is not set]; then
  execute command
fi

I am writing a wrapper around another command. It has it's own usage message if no first argument is set (it is actually an input filename). It has other inputs that I am hardcoding for now. The actual command in the bash script is something like :

command $1 12 3124 534

I want to invoke it's own help message if no $1 was sent to the script.

Upvotes: 0

Views: 141

Answers (1)

kojiro
kojiro

Reputation: 77197

Just check the length of arguments:

if (( $# < 1 )); then
    echo 'There are no arguments, so you can bet that $1 was not set.'
fi

It's usually trivial to check if a variable has a non-empty value in shell:

[ -n "$val" ]

However, if you want to determine if a name has been declared I'll refer you to BashFAQ 83

Upvotes: 4

Related Questions