开发者

How to specify a default param in unix?

开发者 https://www.devze.com 2023-01-27 08:07 出处:网络
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 sho

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

精彩评论

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

关注公众号