19

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

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

4 Answers 4

16

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

Sign up to request clarification or add additional context in comments.

2 Comments

It also works in Bourne, Korn and POSIX shells, so it is widely usable. It does not work in C Shell derivatives, but then, sea shells are best left on the sea shore.
If an empty string can be a valid input, you have to use ${parameter-word} - It will not clobber empty strings.
12
#!/bin/sh
MY_PARAM=${1:-default}

echo $MY_PARAM

Comments

11

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.

Comments

-1

Perhaps I don't understand your question well, yet I would feel inclined to solve the problem in a less sophisticated manner:

                     ! [[ ${1} ]]   &&   declare $1="DEFAULT"

Hope that helps.

1 Comment

If $1 is not set, the name in declare $1="DEFAULT" is empty, which is not going to help. If it is set (for example, the script was invoked as ./script abc), then the declare you suggest makes the variable abc equal to DEFAULT without touching $1. You simply cannot set 'positional parameters' ($1, $2, etc) that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.