pgup12 发表于 2018-8-18 11:49:01

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

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

页: [1]
查看完整版本: 《shell编程实战》第2章shell脚本入门(下)