《shell编程实战》第2章shell脚本入门(下)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《shell编程实战》第2章shell脚本入门(下)相关的知识,希望对你有一定的参考价值。

1、sh和./的区别
[[email protected] ~]# cat test.sh
echo I am thzzc1994
[[email protected] ~]# sh test.sh
I am thzzc1994
[[email protected] ~]# bash test.sh
I am thzzc1994
[[email protected] ~]# ./test.sh
-bash: ./test.sh: 权限不够
想要让./可以执行,需要在用户位加权限x(可执行exec的意思),
在我的环境下执行chmod u+x test.sh等价于chmod 744 test.sh:
[[email protected] ~]# ll test.sh
-rw-r--r-- 1 root root 20 4月 22 11:45 test.sh
[[email protected] ~]# chmod u+x test.sh(chmod 744 test.sh)
[[email protected] ~]# ll test.sh
-rwxr--r-- 1 root root 20 4月 22 11:45 test.sh
[[email protected] ~]# ./test.sh
I am thzzc1994
提示:由于./方法每次都需要给定执行权限,但容易被忘记,且多了一些步骤,增加了复杂性,所以一般都是用sh执行。
2、sh和source的区别
[[email protected] ~]# echo ‘userdir=pwd‘>test.sh
[[email protected] ~]# cat test.sh
userdir=pwd
[[email protected] ~]# sh test.sh
[[email protected] ~]# echo $userdir

在当前shell查看userdir的值,发现值是空的。现在以同样的步骤改用source来执行,再来看看userdir变量的值:
[[email protected] ~]# source test.sh
[[email protected] ~]# echo $userdir
/root
结论:通过source或.加载执行过的的脚本,由于是在当前shell中执行脚本,因此在脚本结束之后,脚本中的变量(包括函数)值在当前shell中依然存在,而sh和bash执行脚本都会启动新的子shell执行,执行完后回到父shell,变量和函数值无法保留。
平时在进行shell脚本开发时,如果脚本中有引用或执行其他脚本的内容或配置文件的需求时,最好用.或source先加载该脚本或配置文件,再加载脚本的下文。
趁热打铁:这是某互联网公司linux运维职位笔试题。请问echo $user的返回结果为()
[[email protected] ~]# cat test.sh
user=whoami
[[email protected] ~]# sh test.sh
[[email protected] ~]# echo $user
(A)当前用户
(B)thzzc1994
(C)空值
前面已经讲过了,sh的变量值,父shell是得不到的。所以这题可以看成只有一句话,那就是
[[email protected] ~]# echo $user
结果当然是空值了。
结论:(1)子shell脚本会直接继承父shell的变量、函数等,就好像儿子随父亲姓,基因继承父亲的,反之则不可以。
(2)如果希望父shell继承子shell,就先用source或.加载子shell脚本,后面父shell就能用子shell的变量和函数值了。
3、介绍一个简单编辑脚本命令cat>,能大大方便开发
cat>test.sh,输入内容后按回车,再按Ctrl+d组合键结束编辑。
[[email protected] ~]# cat>test.sh
echo I am thzzc1994 [Enter][Ctrl+d]
[[email protected] ~]# sh test.sh
I am thzzc1994

以上是关于《shell编程实战》第2章shell脚本入门(下)的主要内容,如果未能解决你的问题,请参考以下文章

《shell编程实战》第3章shell变量基础(下)

《shell编程实战》第4章shell变量进阶(上)

linux shell 脚本 入门到实战详解[⭐建议收藏!!⭐]

linux shell 脚本 入门到实战详解[⭐建议收藏!!⭐]

linux shell 脚本 入门到实战详解[⭐建议收藏!!⭐]

第3章 Shell脚本入门