← 返回首页
Linux高级程序设计(三)
发表时间:2021-10-29 23:05:32
自定义变量

1.自定义变量

Shell编程中,使用变量无需事先声明,同时变量名的命名须遵循如下规则: - 首个字符必须为字母(a-z,A-Z) - 中间不能有空格,可以使用下划线(_) - 不能使用标点符号 - 不能使用bash里的关键字(可用help命令查看保留关键字)

需要给变量赋值时,可以这么写: 变量名=值

要取用一个变量的值,只需在变量名前面加一个$ ( 注意: 给变量赋值的时候,不能在"="两边留空格 )

实例:

#!/bin/bash
#定义变量
num=100
n=$num
echo "num=$num"
echo "n=$n"
#清除变量num
unset num
echo "******清除num之后*******"
echo "num=$num"
echo "n=$n"

2.从终端读取变量

read: 从终端读取变量 readonly: 只读变量,不能修改。

实例:

#!/bin/bash
#从控制台输入姓名
read name
echo "name=$name"
name=lisi
echo "name=$name"

read读取多个变量。

#!/bin/bash
#从控制台输入姓名性别和年龄
echo "please input you name,gender and age"
read name gender age
echo "hello,you name is $name,$gender and $age years old!"

终端执行该shell脚本。

[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./hello.sh
please input you name,gender and age
zhangsan male 20
hello,you name is zhangsan,male and 20 years old!

readonly定义只读变量。

#!/bin/bash
#从控制台输入价格
readonly price=100
echo "price=$price"
price=999
echo "price=$price"