开发者

Default values for the arguments to a Unix shell script?

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

Ho开发者_如何学编程w 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}?


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


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.


#!/bin/sh
MY_PARAM=${1:-default}

echo $MY_PARAM


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜