Shell 变量

定义与引用、单双引号区别、只读与删除、环境变量、命令替换。

Beginner
Key Points赋值等号两边不能有空格;双引号会展开变量,单引号原样输出;子进程要看到变量必须 export。

定义与引用

Bash
name="Alice"
age=30
echo "name=$name age=$age"
echo "name=${name}"
Output
name=Alice age=30
name=Alice

No 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
QuoteExpands variablesKeeps spacesUse
"..."YesYesMost of the time
'...'NoYesLiteral text, regex, JSON
noneYesNo — word splittingAlmost 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 set

export 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.

Friends & Partners