Bash 脚本入门
Alex Scriven
Data Scientist
与其他语言类似,可用等号赋值变量。
var1="Moon"
然后用 $ 引用。
echo $var1
Moon
按需命名变量(要有意义):
firstname='Cynthia' lastname='Liu'echo "Hi there" $firstname $lastname
Hi there Cynthia Liu
两个变量都被输出了——不错!
若漏写 $,就不是变量!
firstname='Cynthia'
lastname='Liu'
echo "Hi there " firstname lastname
Hi there firstname lastname
Bash 在创建变量时对空格很严格。请勿添加空格!
var1 = "Moon"
echo $var1
script.sh: line 3: var1: command not found
在 Bash 中,不同引号有不同含义,影响创建与打印变量。
'sometext'):Shell 原样解释其中内容"sometext"):除 $ 与反引号外原样解释最后一种会创建"壳中之壳",如下所示。用于调用命令行程序。用反引号完成。
让我们看看不同变量创建方式的效果
now_var='NOW'now_var_singlequote='$now_var' echo $now_var_singlequote
$now_var
now_var_doublequote="$now_var"
echo $now_var_doublequote
NOW
date 程序可用于演示反引号
该程序的常规输出:
date
Mon 2 Dec 2019 14:07:10 AEDT
现在用一下"壳中之壳":
rightnow_doublequote="The date is `date`."
echo $rightnow_doublequote
The date is Mon 2 Dec 2019 14:13:35 AEDT.
已调用 date 程序,捕获其输出并与 echo 内联拼接。
我们用了一个壳中之壳!
反引号有等价写法:
rightnow_doublequote="The date is `date`."
rightnow_parentheses="The date is $(date)."
echo $rightnow_doublequote
echo $rightnow_parentheses
The date is Mon 2 Dec 2019 14:54:34 AEDT.
The date is Mon 2 Dec 2019 14:54:34 AEDT.
二者效果相同,但反引号较旧。现代更常用括号写法。参见 http://mywiki.wooledge.org/BashFAQ/082
Bash 脚本入门