Shell
变量
基本操作
定义变量
定义变量时,**=**的两边不能加空格
name="test" #ok
name = "test" #error
可以使用语句给变量赋值
for file in ${ls /etc}; do
echo ${file}
done
${file}等价于$file,但是为了区分,推荐使用${file}
echo "file name is ${file}_test" #OK
echo "file name is $file_test" #Error 会将$file_test当作一个变量名
使用变量
echo ${name}
删除变量
unset <variable_name>
使变量变为只读变量
readonly <variable_name>
删除只读变量
#需安装gbd
cat << EOF | sudo gdb
attach $$
call unbind_variable("变量名")
detach
EOF
shell内使用命令
$(command)
`command`
执行运算
#方法1,中括号[]
$[1+1]
#方法2,双小括号,等同于let
$((3+2))
#方法3,let、expr表达式
变量类型
-
局部变量:在脚本或者命令中定义,仅在当前shell实例中有效,其他shell启动的程序不能访问局部变量
-
环境变量:所有的程序,包括shell启动的程序,都能访问环境变量,必要时shell脚本也可以定义环境变量
-
shell变量:shell变量是由shell程序设置的特殊变量。shell变量中有一部分是环境变量,有一部分是局部变量,这些变量保证了shell
的正常运行
Shell字符串
单引号
- 单引号的任何内容都会原样输出,单引号字符串中的变量是无效的
- 单引号字串中不能出现一个单独的引号,即使转义后也不可以
双引号
- 双引号里可以有变量
- 双引号里可以出现转义字符
name="test"
#使用双引号
result="hello,"$name" !"
result1="hello,${name} !"
echo $result $result1
#使用单引号
result='hello '$name' !'
result1='hello ${name}'
echo $result $result1
##result
hello test hello test
hello test hello ${name}
获取字符串长度
name="hankun"
echo ${#hankun} #输出6
提取子字符串
name="hankun"
echo ${hankun:1:3} #输出ank