Linux Shell 脚本编程 入门

查看当系统有什么shell解释器:cat /etc/shells 

 CentOs默认用的是 bash    :  echo $SHELL

Shell 脚本入门

1、脚本格式:

脚本要以  #!/bin/bash  开头 用来指定解析器

创建第一个脚本 hello.sh:

#  编写脚本  也可以不写.sh指定后缀
vim hello.sh
#!/bin/bash      
echo hello world
echo "hello world bash " >> lxw.txt

第一行   #!/bin/bash   用来指定解析器bash

第二行输出一行hello world

第三行  将 hello world bash 追加到 lxw.txt文件中

执行脚本:

bash 脚本名称          

sh 脚本名称

 文件名执行脚本   ./hello.sh

会发现权限不够,因为当前的用户权限是读写  rw-,并没有可执行权限x

我们就需要更改脚本文件权限

# 方式一hello.sh 脚本的+x 权限
chmod +x hello.sh
#  方式二   二进制更改
chmod 744 hello.sh

发现更改权限之后可以用脚本名称直接去执行脚本了

source hello.sh    .  hello.sh  执行脚本 

 这里的 . 脚本名  跟之前的./是不一样的   ./是相对路径  这里的 . 是shell内嵌命令  type source  

source  对比 bash  sh 的区别

前两种方式(bash、sh)都是在当前 shell 中打开一个子 shell 来执行脚本内容,当脚本内容结束,则子 shell 关闭,回到父 shell 中。
第三种,也就是使用在脚本路径前加“ .”或者 source 的方式,可以使脚本内容在当前 shell 里执行,而无需打开子 shell !这也是为什么我们每次要修改完 /etc/profile 文件以后,需要 source 一下的原因。
开子 shell 与不开子 shell 的区别就在于,环境变量的继承关系,如在子 shell 中设置的
当前变量,父 shell 是不可见的

猜你喜欢

转载自blog.csdn.net/weixin_46310452/article/details/126450730