P6 Shell变量详解
变量是什么
shell变量规则
shell作用域
本地变量
变量只针对当前的shell进程,切换shell会导致变量不可见。sh、bash进入子shell,exit退出当前shell。
[root@localhost ~]# name="我是父shell" [root@localhost ~]# echo $name 我是父shell [root@localhost ~]# sh sh-4.2# pstree systemd─┬─ ├─sshd───sshd─┬─bash───sh───pstree │ ├─bash───top │ └─bash───sleep sh-4.2# echo $name
单引号不会替换字符串里面的特殊字符,比如读取变量命令等;双引号会替换。
pstree检查当前的进程树
环境变量、局部变量、位置参数变量、特殊变量、自定义变量
$?上一次命令执行是否成功
P7 父子shell
单双引号、反引号区别
单引号不会替换字符串里面的特殊字符,双引号会。反引号执行执行命令。
[root@localhost ~]# name=fang [root@localhost ~]# name2='$name' [root@localhost ~]# echo $name2 $name [root@localhost ~]# name3="$name" [root@localhost ~]# echo $name3 fang
不同执行方式对应的是否开启子shell
. /cars. sh 和source不开启子进程
./cars.sh 和bash执行开启子进程
P8 环境变量
检查环境变量的命令、变量配置文件
set 输出所有全局变量和当前shell的本地变量、局部变量
多命令执行
分号分隔
环境变量加载顺序
P10 特殊变量
位置参数变量
[root@localhost opt]# bash hello.sh arg1 arg2 arg3 $1: arg1 $2: arg2 $0: hello.sh $#:3 $@: arg1 arg2 arg3 $*: arg1 arg2 arg3
状态变量
- $? 上次命令执行的返回值。 0是运行成功,非0失败
- $$ 执行脚本的当前shell的PID
- $!上一次后台进程的PID。 首先要启动一个后台进程 nohup命令可以启动后台进程
- $_ 返回上次命令的最后一个位置参数
特殊参数参照方式 man bash 搜索 Special Param
(1)exit 119 返回时此脚本返回119码
![]()
(2)nohup 命令 命令参数 & 后台运行参数,shell关闭也不停止。如果相关掉,可以ps aux | grep nohup 然后找到pid kill -9 强制关闭。
nohup 命令 命令参数 & 1>/dev/null 后台不关闭终端运行命令且将nohup的输出定向到垃圾桶。 nohup命令会生成 nohup.out文件