开发者

How to specify a default param in unix?

Say I have the function shoutout inside my .profile file. When I run shoutout 'Hello', the function prints out Hello, which is the expected response. However, I'd like to be able to simply call shoutout with no parameters and have the function pr开发者_开发问答int out Foobar.

How do I specify a default value for $1 with or without variables? Thanks!

shoutout() {
    echo $1
}


shoutout() {
    echo ${1:-Foobar}
}

EDIT: Thanks to @ephemient for this extra tid-bit that I wasn't aware of...

To avoid confusing an empty-string argument as a missing argument, omit the colon (:):

shoutout() {
    echo ${1-Foobar}
}

$ shoutout
Foobar
$ shoutout ""

$


shoutout() {
    if [ $# -eq 0 ]; then
        echo No arguments.
    else
        echo $1
    fi
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜