1.1 Shell的基本元素
声明:使用那一种解释器来解释并执行当前的脚本。#!/bin/bash
命令:可执行的语句,实现程序的功能。
注释:单行注释,使用 # 号来进行注释,另一种是多行注释 :<<BLOCK 注释内容 BLOCK
赋予脚本可执行权限
1.2 Shell脚本规范
- 脚本名称尽量做见名知意
- 在脚本的开头指定解释器
- 在开头增加版权信息
- 尽量使用系统命令,而少使用管道
- 尽量不要使用中文注释
- 代码注重缩进
1.3 Shell脚本编写方式
-
交互式执行
[root@openEuler ~]# for name in `ls /etc` > do > echo $name > done
-
作为程序文件执行(推荐使用)
[root@openEuler ~]# vim for_test.sh #!/bin/bash echo $USER
1.4 Shell脚本执行方式
bash for_test.sh
命令来执行,它会产生一个子 Shell,然后在子 Shell 中运行脚本,执行完后回去父Shell。sh for_test.sh
命令来执行,它也会产生一个子 Shell,然后在子 Shell 中运行脚本,执行完后回去父Shell。./for_test.sh
命令来执行,它也会产生一个子Shell,不同点在于它需要有 x 权限。. for_test.sh
命令来执行,使用是文件中定义的解释器,不会产生子 Shell,它是在当前的环境中执行的。source for_test.sh
命令来执行,它的作用与 . 执行一样
[root@openEuler ~]# sh for_test.sh
root
[root@openEuler ~]# ll
total 32
-rw-------. 1 root root 881 Mar 16 20:10 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4096 Mar 17 10:29 d1
-rw-r--r--. 1 root root 24 Mar 23 14:32 for_test.sh
-rw-r--r--. 1 root root 49 Mar 16 21:07 hehe.txt
-rw-r--r--. 1 root root 35 Mar 17 09:51 message.txt
-rwxr-xr-x. 1 root root 26 Mar 17 11:18 my.sh
-rw-r--r--. 1 root root 183 Mar 16 21:03 passwd
-rw-r--r--. 1 root root 54 Mar 17 10:21 test.txt
[root@openEuler ~]# ./for_test.sh
-bash: ./for_test.sh: Permission denied
[root@openEuler ~]# chmod a+x for_test.sh
[root@openEuler ~]# ./for_test.sh
root
[root@openEuler ~]# . for_test.sh
root
[root@openEuler ~]# source for_test.sh
root
1.5 Shell退出状态
在 Linux 中执行命令后,会有一个状态,如果值为 0 表示之前执行的命令是正常执行的,如果是非0则表示前一条命令执行是有错误发生。
[root@openEuler ~]# source for_test.sh
root
[root@openEuler ~]# echo $?
0
[root@openEuler ~]# source for_test.sh1
-bash: for_test.sh1: No such file or directory
[root@openEuler ~]# echo $?
1