一、sh和./的区别
[root@thzzc1994 ~]# cat test.sh
echo I am thzzc1994
[root@thzzc1994 ~]# sh test.sh
I am thzzc1994
[root@thzzc1994 ~]# bash test.sh
I am thzzc1994
[root@thzzc1994 ~]# ./test.sh
-bash: ./test.sh: 权限不够
想要让./能够执行,须要在用户位加权限x(可执行exec的意思),
在个人环境下执行chmod u+x test.sh等价于chmod 744 test.sh:
[root@thzzc1994 ~]# ll test.sh
-rw-r--r-- 1 root root 20 4月 22 11:45 test.sh
[root@thzzc1994 ~]# chmod u+x test.sh(chmod 744 test.sh)
[root@thzzc1994 ~]# ll test.sh
-rwxr--r-- 1 root root 20 4月 22 11:45 test.sh
[root@thzzc1994 ~]# ./test.sh
I am thzzc1994
提示:因为./方法每次都须要给定执行权限,但容易被忘记,且多了一些步骤,增长了复杂性,因此通常都是用sh执行。
二、sh和source的区别
[root@thzzc1994 ~]# echo 'userdir=pwd
'>test.sh
[root@thzzc1994 ~]# cat test.sh
userdir=pwd
[root@thzzc1994 ~]# sh test.sh
[root@thzzc1994 ~]# echo $userdirlinux
在当前shell查看userdir的值,发现值是空的。如今以一样的步骤改用source来执行,再来看看userdir变量的值:
[root@thzzc1994 ~]# source test.sh
[root@thzzc1994 ~]# echo $userdir
/root
结论:经过source或.加载执行过的的脚本,因为是在当前shell中执行脚本,所以在脚本结束以后,脚本中的变量(包括函数)值在当前shell中依然存在,而sh和bash执行脚本都会启动新的子shell执行,执行完后回到父shell,变量和函数值没法保留。
平时在进行shell脚本开发时,若是脚本中有引用或执行其余脚本的内容或配置文件的需求时,最好用.或source先加载该脚本或配置文件,再加载脚本的下文。
趁热打铁:这是某互联网公司linux运维职位笔试题。请问echo $user的返回结果为()
[root@thzzc1994 ~]# cat test.sh
user=whoami
[root@thzzc1994 ~]# sh test.sh
[root@thzzc1994 ~]# echo $user
(A)当前用户
(B)thzzc1994
(C)空值
前面已经讲过了,sh的变量值,父shell是得不到的。因此这题能够当作只有一句话,那就是
[root@thzzc1994 ~]# echo $user
结果固然是空值了。
结论:(1)子shell脚本会直接继承父shell的变量、函数等,就好像儿子随父亲姓,基因继承父亲的,反之则不能够。
(2)若是但愿父shell继承子shell,就先用source或.加载子shell脚本,后面父shell就能用子shell的变量和函数值了。
三、介绍一个简单编辑脚本命令cat>,能大大方便开发
cat>test.sh,输入内容后按回车,再按Ctrl+d组合键结束编辑。
[root@thzzc1994 ~]# cat>test.sh
echo I am thzzc1994 [Enter][Ctrl+d]
[root@thzzc1994 ~]# sh test.sh
I am thzzc1994shell