父子shell变量经典案例
###案例1,
###1.开启子shell的执行方式
[root@localhost myshell]# cat mak_var.sh
name="脚本变量"
[root@localhost myshell]# name="当前shell进程变量"
[root@localhost myshell]# bash mak_var.sh
[root@localhost myshell]# echo ${name}
当前shell进程变量 #########??????????????????????????
[root@localhost myshell]#
######2.不开启子shell的执行方式,用soruce 或者点符号
当前shell进程变量
[root@localhost myshell]# source mak_var.sh
[root@localhost myshell]# echo ${name}
脚本变量 ####
[root@localhost myshell]#
解答:1)每次调用bash/sh解释器,都会开启一个子shell,因此不保留当前的shell变量,可通过pstree命令检查进程数. 2)调用source或者点符号,在当前shell环境价值脚本,因此保留变量
注意:Linux中反引号中的命令会被保留下来,执行结果也能返回给变量
###案例2:请问,会输出什么内容
#A 当前用户
#B 超哥
#C 空
####答案是C;sh是新开一个子shell;如果要在当前shell执行则用source 或点符号
[root@localhost myshell]# cat test.sh
user1=`whoami`:
[root@localhost myshell]# sh test.sh
[root@localhost myshell]# echo $user1
######使用绝对路径或相对路径都是新开shell子进程;测试如下
[root@localhost myshell]# pwd
/home/tmp/myshell
[root@localhost myshell]# ls -lah
总用量 16K
drwxr-xr-x. 2 root root 39 8月 31 16:19 .
drwxr-xr-x. 4 root root 4.0K 8月 31 16:06 ..
-rw-r--r--. 1 root root 20 8月 31 16:07 mak_var.sh
-rw-r--r--. 1 root root 16 8月 31 16:19 test.sh
[root@localhost myshell]# chmod 744 test.sh
[root@localhost myshell]# /home/tmp/myshell/test.sh ###绝对路径
[root@localhost myshell]# echo $user1
[root@localhost myshell]# ./test.sh ###相对路径
[root@localhost myshell]# echo $user1
[root@localhost myshell]# . test.sh
[root@localhost myshell]# echo $user1
root:
[root@localhost myshell]#