Skip to content

二、Shell脚本入门

1、脚本格式

  • Shell 脚本名称命名一般为英文、大写、小写;
  • 不能使用特殊符号、空格来命名;
  • Shell 脚本后缀以.sh 结尾;
  • 不建议 Shell 命名为纯数字,一般以脚本功能命名。
  • Shell 脚本内容首行需以#!/bin/bash开头;
  • Shell 脚本中变量名称尽量使用大写字母,字母间不能使用“-”,可以使用“_”;
  • Shell 脚本变量名称不能以数字、特殊符号开头。

2、第一个 Shell 脚本:helloworld.sh

1、需求:创建一个 Shell 脚本,输出 helloworld

2、案例实操:

sh
[root@k8s-node shells]$ touch first_shell.sh
[root@k8s-node shells]$ vim first_shell.sh
 helloworld.sh 中输入如下内容 
#!/bin/bash 
# This is my First shell
# By author xueqimiao
echo "Hello World"
sh
#!/bin/bash  固定格式,定义该脚本所使用的 Shell 类型;
# This is my First shell #号表示注释,没有任何的意义,SHELL 不会解析它;
# By author xueqimiao
echo "Hello World" Shell 脚本主命令,执行该脚本呈现的内容。

Shell 脚本编写完毕,如果运行该脚本,运行用户需要有执行权限,可以使用 chmod o+x first_shell.sh 赋予可执行权限。然后**./first_shell.sh** 执行即可,还可以直接使用命 令执行: /bin/sh first_shell.sh 直接运行脚本,不需要执行权限,最终脚本执行显示效果 一样。

sh
chmod o+x first_shell.sh
./first_shell.sh
sh
# 调试shell脚本
sh -x first_shell.sh

3、脚本的常用执行方式

1、采用 bash 或 sh+脚本的相对路径或绝对路径(不用赋予脚本+x 权限)

sh+脚本的相对路径

sh
sh ./helloworld.sh

sh+脚本的绝对路径

sh
sh /home/xue/shells/helloworld.sh

bash+脚本的相对路径

sh
bash ./helloworld.sh

bash+脚本的绝对路径

sh
bash /home/xue/shells/helloworld.sh

2、采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)

  1. 首先要赋予 helloworld.sh 脚本的+x 权限
sh
chmod +x helloworld.sh
  1. 执行脚本

    1. 相对路径
    sh
    ./helloworld.sh
    1. 绝对路径
    sh
    /home/xue/shells/helloworld.sh

注意:第一种执行方法,本质是 bash 解析器帮你执行脚本,所以脚本本身不需要执行权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。

3、【了解】在脚本的路径前加上“.”或者 source

有以下脚本

sh
cat test.sh
#!/bin/bash
A=5
echo $A

分别使用 sh,bash,./ 和 . 的方式来执行,结果如下:

sh
[root@k8s-node shells]$ bash test.sh
[root@k8s-node shells]$ echo $A

[root@k8s-node shells]$ sh test.sh
[root@k8s-node shells]$ echo $A

[root@k8s-node shells]$ ./test.sh
[root@k8s-node shells]$ echo $A

[root@k8s-node shells]$ . test.sh
[root@k8s-node shells]$ echo $A
5

原因:

前两种方式都是在当前 shell 中打开一个子 shell 来执行脚本内容,当脚本内容结束,则子 shell 关闭,回到父 shell 中。

第三种,也就是使用在脚本路径前加“.”或者 source 的方式,可以使脚本内容在当前 shell 里执行,而无需打开子 shell!这也是为什么我们每次要修改完/etc/profile 文件以后,需要 source 一下的原因。

开子 shell 与不开子 shell 的区别就在于,环境变量的继承关系,如在子 shell 中设置的 当前变量,父 shell 是不可见的。

4、脚本字体颜色

sh
echo -e "\033[30m黑色字\033[0m"  
echo -e "\033[31m红色字\033[0m"  
echo -e "\033[32m绿色字\033[0m"  
echo -e "\033[33m黄色字\033[0m"  
echo -e "\033[34m蓝色字\033[0m"  
echo -e "\033[35m紫色字\033[0m"  
echo -e "\033[36m天蓝字\033[0m"  
echo -e "\033[37m白色字\033[0m"