shell中的变量

变量的定义

基本定义方式

定义shell变量时,直接使用 变量名=变量值 的格式就可以了,如下:

1
shell_variable="some variable"

注意: 变量名和等号之间不能有空格

语句中赋值

变量也可以直接在语句中赋值:

1
for skill in Ada Coffe Action Java:

变量命名规则

  • 命名只能使用英文字母,数字和下划线,首个字符不能以数字开头

  • 中间不能有空格,可以使用下划线(_)

  • 不能使用标点符号

  • 不能使用bash里的关键字

变量的使用

使用一个定义过的变量,只要在变量名前加美元符号即可,如:

1
2
echo $shell_variable
echo ${shell_variable}

在使用括号时加上大括号主要是为了区分变量的边界,如:

1
2
3
4
for skill in Ada Coffe Action Java;
do
echo "I am goot at ${skill}Script"
done

在这里如果不加大括号,shell将把skillScript当做变量名执行

设置只读变量

使用readonly命令可以将变量定义为只读变量,只读变量的值不能被改变。

1
2
myUrl="http://google.com"
readonly myUrl

变量的删除

使用unset命令可以删除变量。语法:

1
unset shell_variable

测试脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# !/bin/bash
# 声明一个变量
shell_variable="some variable"
# 使用变量的两种方式
echo $shell_variable
echo ${shell_variable}
# 用语句给变量赋值
for skill in Ada Coffe Action Java;
do
echo "I am goot at ${skill}Script"
done
# 只读变量
myUrl="http://www.google.com"
readonly myUrl
# 删除变量
unset shell_variable
echo $shell_variable

执行结果:

1
2
3
4
5
6
some variable
some variable
I am goot at AdaScript
I am goot at CoffeScript
I am goot at ActionScript
I am goot at JavaScript