Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values to a unix shell script?

Normally when a parameter is passed to a shell script, the value goes into ${1} for the first paramater, ${2} for the second, etc.

How can I set the default values for these parameters, so if no parameter is passed to the script, we can use a default value for ${1}?

like image 969
coffee Avatar asked Jul 08 '11 17:07

coffee


2 Answers

You can't, but you can assign to a local variable like this: ${parameter:-word} or use the same construct in the place you need $1. this menas use word if _paramater is null or unset

Note, this works in bash, check your shell for the syntax of default values

like image 135
Op De Cirkel Avatar answered Sep 28 '22 18:09

Op De Cirkel


You could consider:

set -- "${1:-'default for 1'}" "${2:-'default 2'}" "${3:-'default 3'}"

The rest of the script can use $1, $2, $3 without further checking.

Note: this does not work well if you can have an indeterminate list of files at the end of your arguments; it works well when you can have only zero to three arguments.

like image 40
Jonathan Leffler Avatar answered Sep 28 '22 16:09

Jonathan Leffler