Shell 变量
定义与引用、单双引号区别、只读与删除、环境变量、命令替换。
Key Points赋值等号两边不能有空格;双引号会展开变量,单引号原样输出;子进程要看到变量必须 export。
定义与引用
Bash
name="Alice"
age=30
echo "name=$name age=$age"
echo "name=${name}"Output
name=Alice age=30
name=AliceNo spaces around = in an assignment — name = "Alice" is parsed as running the name command. $name and ${name} are equivalent, but use braces when followed by letters or digits, e.g. ${name}_bak.
单引号与双引号
Bash
name="Alice"
echo "hello $name"
echo 'hello $name'
echo "today is $(date +%Y) ok"Output
hello Alice
hello $name
today is 2026 ok| Quote | Expands variables | Keeps spaces | Use |
|---|---|---|---|
"..." | Yes | Yes | Most of the time |
'...' | No | Yes | Literal text, regex, JSON |
| none | Yes | No — word splitting | Almost never |
只读与删除
Bash
readonly PI=3.14
echo "$PI"
unset name
echo "name is now [${name:-empty}]"Output
3.14
name is now [empty]环境变量
Bash
export APP_ENV="prod"
echo "$APP_ENV"
printenv HOME > /dev/null && echo "HOME is set"Output
prod
HOME is setexport puts the variable into the environment so child processes see it. Without it, bash -c 'echo $APP_ENV' prints nothing.
命令替换与算术
Bash
n=$((2 + 3 * 4))
echo "n=$n"
count=3
echo "many: $((count > 2))"
echo "float: $(awk 'BEGIN{printf "%.2f", 10/3}')"Output
n=14
many: 1
float: 3.33$(( )) is integer-only: 10/3 is 3, not 3.33. For decimals use awk or bc.定义与引用
Bash
name="Alice"
age=30
echo "name=$name age=$age"
echo "name=${name}"Output
name=Alice age=30
name=Alice赋值时 = 两边不能有空格,name = "Alice" 会被当成执行 name 命令。引用时 $name 与 ${name} 等价,但后面紧跟字母数字时必须用花括号,如 ${name}_bak。
单引号与双引号
Bash
name="Alice"
echo "hello $name"
echo 'hello $name'
echo "today is $(date +%Y) ok"Output
hello Alice
hello $name
today is 2026 ok| 引号 | 展开变量 | 保留空格 | 用途 |
|---|---|---|---|
| 双引号 | 是 | 是 | 绝大多数场景 |
| 单引号 | 否 | 是 | 字面文本、正则、JSON |
| 不加引号 | 是 | 否,会按空格拆分 | 几乎不要用 |
只读与删除
Bash
readonly PI=3.14
echo "$PI"
unset name
echo "name is now [${name:-empty}]"Output
3.14
name is now [empty]环境变量
Bash
export APP_ENV="prod"
echo "$APP_ENV"
printenv HOME > /dev/null && echo "HOME is set"Output
prod
HOME is setexport 把变量放进环境,子进程才看得见。不加 export 的变量只属于当前 shell,bash -c 'echo $APP_ENV' 会是空的。
命令替换与算术
Bash
n=$((2 + 3 * 4))
echo "n=$n"
count=3
echo "many: $((count > 2))"
echo "float: $(awk 'BEGIN{printf "%.2f", 10/3}')"Output
n=14
many: 1
float: 3.33Shell 的
$(( )) 只做整数运算,10/3 得 3 不是 3.33。要小数就用 awk、bc,或者换语言。