shell脚本基本语法

2.1 shell脚本的用途

2.2 shell脚本基本结构

【特点】shell脚本编程:是基于过程式、解释执行的语言

【格式】基本格式要求:首行需要写明命令解释器,称之为【shebang机制】(shebang是 #! 的音译)

#!/bin/bash
#!/usr/bin/python
#!/usr/bin/perl

=

2.3 创建shell脚本过程

1 首行与注释

使用文本编辑器来创建文本文件,如vim

第一行必须包括shell声明序列:#!
添加注释:注释以 # 开头(必要的描述信息,方便后期维护)

=

2 加执行权限

给予执行权限,在命令行上指定脚本的绝对或相对路径

chmod +x shell.sh

=

3 运行本地脚本

【原理】直接运行解释器,将脚本作为解释器程序的参数运行

运行脚本的方法:

# 文件有执行权限:
## 直接执行文件
xxx.sh
/path/xxx.sh

# 文件无执行权限:
sh xxx.sh
bash xxx.sh
. xxx.sh

bash < /data/hello.sh
cat /data/hello.sh | bash

=

4 远程执行脚本

在本机运行 远程主机的脚本

sshpass -p PASSWD ssh [user@]x.x.x.x  CMD
注:若第一次连接,需要选项 -o StrictHostKeyChecking=no

# 例如:在本机执行centos8上的/root/auto_CA.sh脚本
sshpass -p centos ssh 10.0.0.8  bash /root/auto_CA.sh

=

在远程主机运行 本机的脚本

ssh [user@]x.x.x.x  CMD

# 例如:在centos8运行【本机pwd的】test脚本
ssh root@10.0.0.8  /bin/bash < test.sh 【确保test.sh在当前目录】

=


=

2.4 脚本注释规范

1、第一行一般为调用使用的语言
2、程序名,避免更改文件名为无法找到正确的文件
3、版本号
4、最后更改的时间
5、作者相关信息
6、该程序的作用,及注意事项
7、最后是各版本的更新简要说明


=

2.5 第一个脚本

#!/bin/bash

echo "hello world"   

执行方式:

[root@centos8/data]# /data/hello.sh 
hello world
[root@centos8/data]# ./hello.sh
hello world
[root@centos8/data]# bash hello.sh 
hello world
[root@centos8/data]# sh hello.sh 
hello world
[root@centos8/data]# . hello.sh 
hello world

=

=

2.6 脚本调试

1 命令错误

一般不影响后续内容

=

2 语法错误
# 检测脚本中的语法错误
bash -n /path/to/some_script   # 提示的错误信息【未必准确】

若无任何反馈消息表示无语法错误

=

3 逻辑错误
# 逐行执行检查
bash -x /path/to/some_script

= wan

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值