Unix scrip 11 - variables III 大括号

本文详细介绍了Shell脚本中如何利用特殊符号来为未定义或空值的变量设置默认值,包括使用`:-`和`:=`语法,并通过实例展示了其在用户输入场景的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

As we mentioned in Variables - Part I, curly brackets around a variable avoid confusion:

foo=sun
echo $fooshine     # $fooshine is undefined
echo ${foo}shine   # displays the word "sunshine"
That's not all, though - these fancy brackets have a another, much more powerful use. We can deal with issues of variables being undefined or null (in the shell, there's not much difference between undefined and null).

Using Default Values
Consider the following code snippet which prompts the user for input, but accepts defaults:
#!/bin/sh
echo -en "What is your name [ `whoami` ] "
read myname
if [ -z "$myname" ]; then
  myname=`whoami`
fi
echo "Your name is : $myname"
The "-en" to echo tells it not to add a linebreak. On some systems, you use a "\c" at the end of the line, instead.
This script runs like this:
steve$ ./name.sh
What is your name [ steve ]
Your name is : steve

... or, with user input:

steve$ ./name.sh
What is your name [ steve ] foo
Your name is : foo
This could be done better using a shell variable feature. By using curlybraces and the special ":-" usage, you can specify a default value to useif the variable is unset:
echo -en "What is your name [ `whoami` ] "
read myname
echo "Your name is : ${myname:-`whoami`}"
This could be considered a special case - we're using the output of thewhoami command, which prints your login name (UID). The more canonicalexample is to use fixed text, like this:
echo "Your name is : ${myname:-John Doe}"
As with other use of the backticks, `whoami` runs in a subshell, so any cd commands, or setting any other variables, within the backticks, will not affect the currently-running shell.
Using and Setting Default Values
There is another syntax, ":=", which sets the variable to the defaultif it is undefined:
echo "Your name is : ${myname:=John Doe}"
This technique means that any subsequent access to the $myname variable will always get a value, either entered by the user, or "John Doe" otherwise.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值