1.Shell脚本基础

1.1 Shell的基本元素

声明:使用那一种解释器来解释并执行当前的脚本。#!/bin/bash

命令:可执行的语句,实现程序的功能。

注释:单行注释,使用 # 号来进行注释,另一种是多行注释 :<<BLOCK 注释内容 BLOCK

赋予脚本可执行权限

1.2 Shell脚本规范

  1. 脚本名称尽量做见名知意
  2. 在脚本的开头指定解释器
  3. 在开头增加版权信息
  4. 尽量使用系统命令,而少使用管道
  5. 尽量不要使用中文注释
  6. 代码注重缩进

1.3 Shell脚本编写方式

  1. 交互式执行

    [root@openEuler ~]# for name in `ls /etc`
    > do
    > echo $name
    > done
    
  2. 作为程序文件执行(推荐使用)

    [root@openEuler ~]# vim for_test.sh
    
    #!/bin/bash
    
    echo $USER
    

1.4 Shell脚本执行方式

  1. bash for_test.sh 命令来执行,它会产生一个子 Shell,然后在子 Shell 中运行脚本,执行完后回去父Shell。
  2. sh for_test.sh 命令来执行,它也会产生一个子 Shell,然后在子 Shell 中运行脚本,执行完后回去父Shell。
  3. ./for_test.sh 命令来执行,它也会产生一个子Shell,不同点在于它需要有 x 权限。
  4. . for_test.sh 命令来执行,使用是文件中定义的解释器,不会产生子 Shell,它是在当前的环境中执行的。
  5. 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
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

acro_09

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值