Shell脚本编程基础之shell脚本基本用法

shell用途

  • 批量执行
  • 非干预自动执行
  • 自动化运维
  • 标准化

shell结构

  • 首行 #!/bin/bash ## bash是指定解释器
  • 开头注释

  • 命令
  • 函数
  • 控制语句
  • sh后缀 ## 约定俗成

修改.vimrc

修改目录下.vimrc配置文件可以在每次用vim创建shell脚本的时候自动添加抬头注释

脚本执行

  • shell脚本创建后需要添加执行权限才能直接执行
  • shell脚本执行时如果不在环境变量目录,需要添加路径执行
  • 使用bansh +脚本也可以执行未添加执行权限的脚本
  • shell脚本可以通过管道符重定向给bash执行

可以将脚本放在网上,通过curl 将显示出来的脚本传给bash执行

脚本调试

  • bash -n 不执行脚本,检查脚本语法错误
  • bash -x 调试并执行脚本,可以看到脚本执行的过程
[06:11:59 root@C8-3-55 ~]#bash -n userAdd100.sh
[06:12:21 root@C8-3-55 ~]#bash -x userAdd100.sh
+ for i in {1..100}
+ useradd user1
useradd:用户“user1”已存在
++ cat /dev/urandom
++ tr -dc '[:alnum:]'
++ head -c 12
+ PWD=7egorsNNBJYp
+ passwd --stdin user
+ echo 7egorsNNBJYp
+ echo user1:7egorsNNBJYp
+ echo 'hahaha,i creat 1 user by coding !!!'
hahaha,i creat 1 user by coding !!!
* * * 胖并快乐着的死肥宅 * * *
原文地址:https://www.cnblogs.com/bpzblog/p/14512562.html