1.格式要求:首行shebang机制python
#!/bin/bash #!/usr/bin/python #!/usr/bin/perl
2.添加执行权限,在命令行上指定脚本的绝对或者相对路径,也能够运行脚本解释器直接运行脚本linux
一、第一行通常为调用使用的语言面试
二、程序名,避免更改文件名为没法找到正确的文件正则表达式
三、版本号shell
四、更改后的时间数据库
五、做者相关信息express
六、该程序的做用,及注意事项vim
七、最后是各版本的更新简要说明centos
[root@centos8 data]# cat shell.sh #!/bin/bash ls [root@centos8 data]# chmod +x shell.sh #相对路径执行 [root@centos8 data]# ./shell.sh a.txt b.txt linxu.txt message passwd shell.sh systeminfo.sh test vimrc #bash执行 [root@centos8 data]# bash shell.sh a.txt b.txt linxu.txt message passwd shell.sh systeminfo.sh test vimrc #执行远程主机的shell脚本 [root@centos8 data]# #curl -s http://10.0.0.8/hello.sh|bash [root@centos8 ~]#wget -qO - http://www.wangxiaochun.com/testdir/hello.sh |bash
脚本常见的3种错误:安全
bash命令
bash -n:只检测脚本中的语法错误,但没法检查出命令错误,但不真正执行脚本
bash -x:调试并执行脚本
内置变量,如:PS1,PATH,UID,HOSTNAME,$$,BASHPID,PPID,$?,HISTSIZE
用户自定义变量
变量赋值
#变量的赋值能够是如下多种形式 直接字串:name='root' 变量引用:name="$USER" 命令引用:name=`COMMAND` 或者 name=$(COMMAND)
变量引用
$name ${name}
范例
[root@centos8 data]# name='xiaoming' [root@centos8 data]# echo $name xiaoming [root@centos8 data]# user='yonghu' [root@centos8 data]# name="$user" [root@centos8 data]# echo $name yonghu [root@centos8 data]# name=`ls -l /data/` [root@centos8 data]# echo $name total 8 -rw-r--r-- 1 root root 403 Jan 2 17:39 systeminfo.sh -rw-r--r-- 1 root root 110 Jan 3 10:17 test [root@centos8 data]# echo "$name" total 8 -rw-r--r-- 1 root root 403 Jan 2 17:39 systeminfo.sh -rw-r--r-- 1 root root 110 Jan 3 10:17 test
范例:变量追加值
[root@centos8 data]# echo $user yonghu [root@centos8 data]# user+=:xiaoming [root@centos8 data]# echo $user yonghu:xiaoming
显示和删除变量
#set查看全部变量 #unset <name>删除指定变量 #使用上述方式设置变量是临时保存于内存当中,当退出终端就会销毁
说明
环境变量的声明和赋值:
#声明并赋值 export name=VALUE declare -x name=VALUE #或者分两步实现 name=VALUE export name
变量引用:
$name ${name}
显示全部环境变量:
env printenv export declare -x
删除变量
unset
bash的内建环境变量
PATH SHELL USER UID HOME PWD SHLVL #shell的嵌套层数,即深度 LANG MAIL HOSTNAME HISTSIZE _ #下划线 表示前一命令的最后一个参数
只能声明定义,但后续不能修改和删除,即常量;退出当前终端能够销毁声明的只读变量
声明只读变量:
readonly name declare -r name
查看只读变量
readonly [-p] declare -r
在bash shell中内置的变量, 在脚本代码中调用经过命令行传递给脚本的参数
$1, $2, ... 对应第1个、第2个等参数,shift [n]换位置 $0 命令自己,包括路径 $* 传递给脚本的全部参数,所有参数合为一个字符串 $@ 传递给脚本的全部参数,每一个参数为独立字符串 $# 传递给脚本的参数的个数 #清空全部位置变量 set --
范例
[root@centos8 data]# cat arg.sh #!/bin/bash echo "arg1 is $1" echo "arg1 is $2" echo "arg1 is $3" echo "the number of arg is $#" echo "all args is $*" echo "all args is $@" echo "the script name is `basename $0`" [root@centos8 data]# bash arg.sh {1..5} arg1 is 1 arg1 is 2 arg1 is 3 the number of arg is 5 all args is 1 2 3 4 5 all args is 1 2 3 4 5 the script name is arg.sh
rm命令修改
#用户使用rm命令时不删除文件而是移动到/tmp文件夹 [root@centos8 data]# cat rm.sh COLOR="echo -e \E[1;31m" END="\E[0m" DIR=/tmp/`date +%F_%H-%M-%S` mkdir $DIR mv $* $DIR $COLOR move $* to $DIR $END
$?
$?的值为0,表明成功
$?的值是1到255 #表明失败
注意:
$- 变量
[root@centos8 data]# echo $- himBHs
h:hashall,打开选项后,Shell 会将命令所在的路径hash下来,避免每次都要查询。经过set +h将h选 项关闭
i:interactive-comments,包含这个选项说明当前的 shell 是一个交互式的 shell。所谓的交互式shell, 在脚本中,i选项是关闭的 m:monitor,打开监控模式,就能够经过Job control来控制进程的中止、继续,后台或者前台执行等
B:braceexpand,大括号扩展
H:history,H选项打开,能够展开历史列表中的命令,能够经过!感叹号来完成,例如“!!”返回上最近的 一个历史命令,“!n”返回第 n 个历史命令
set 命令
-u 在扩展一个没有设置的变量时,显示错误信息, 等同set -o nounset
-e 若是一个命令返回一个非0退出状态值(失败)就退出, 等同set -o errexit
-o option 显示,打开或者关闭选项
显示选项:set -o
打开选项:set -o 选项
关闭选项:set +o 选项
printf:格式化要输出的数据
printf FORMAT [ARGUMENT]...
经常使用格式替换符
%s 字符串
%f 浮点格式
%b 相对应的参数中包含转义字符时,可使用此替换符进行替换,对应的转义字符会被转 义
%c ASCII字符,即显示对应参数的第一个字符
%d,%i 十进制整数
%o 八进制值
%u 不带正负号的十进制值
%x 十六进制值(a-f)
%X 十六进制值(A-F)
%% 表示%自己
%s 中的数字表明此替换符中的输出字符宽度,不足补空格,默认是右对齐,%-10s表示10个字 符宽,- 表示左对齐
经常使用转义字符
范例
[root@centos8 data]# printf "%d\n" 123 321 123 123 321 123 [root@centos8 data]# printf "(%s) " 1 2 3 (1) (2) (3) [root@centos8 data]# [root@centos8 data]# printf "(%s) " 1 2 3;echo (1) (2) (3) [root@centos8 data]# printf "(%s) " 1 2 3;echo "" (1) (2) (3) [root@centos8 data]# printf "%10s" name;echo name
shell 支持算术运算,但只支持整数,不支持小数
shell运算符
+ - * / % 取模,即取余数,示例:9%4=1,5%3=2 ** 乘方
实现算数运算的方式
1. let var=算数表达式 2. ((var=算数表达式)) 3. var=$[算数表达式] 4. var=$((算数表达式)) 5. delare -i var = 数值 6. echo '算术表达式' | bc 7. var=$(expr arg1 arg2 arg3 ...)
范例
#生成 1 - 50 之间随机数 [root@centos8 data]# echo $[RANDOM%50+1] 12
加强型赋值:
+= i+=10 至关于 i=i+10 -= i-=j 至关于 i=i-j *= /= %= ++ i++,++i 至关于 i=i+1 -- i--,--i 至关于 i=i-1
范例
#i++和++i [root@centos8 ~]#unset i j ; i=1; let j=i++; echo "i=$i,j=$j" i=2,j=1 [root@centos8 ~]#unset i j ; i=1; let j=++i; echo "i=$i,j=$j" i=2,j=2 #使用计算器实现浮点运算 [root@centos8 data]# echo "scale=3;20/3" | bc 6.666
与:&:和0相与,结果为0,和1相与,结果保留原值
1 与 1 = 1 1 与 0 = 0 0 与 1 = 0 0 与 0 = 0
或:|:和1相或结果为1,和0相或,结果保留原值
1 或 1 = 1 1 或 0 = 1 0 或 1 = 1 0 或 0 = 0
非:!
! 1 = 0 ! true ! 0 = 1 ! false
异或:^
相同为假,不一样为真。
1 ^ 1 = 0 1 ^ 0 = 1 0 ^ 1 = 1 0 ^ 0 = 0
范例
#注意区分逻辑运算的二进制值与$?的返回值含义恰好相反 #利用异或能够实现两个变量的数值交换 [root@centos8 data]# x=30;y=20;x=$[x^y];y=$[x^y];x=$[y^x];echo "x=$x y=$y" x=20 y=30
短路运算
短路与
CMD1 短路与 CMD2
第一个CMD1结果为假 (0),总的结果一定为0,所以不须要执行CMD2
短路或
CMD1 短路或 CMD2
第一个CMD1结果为真 (1),总的结果一定为1,所以不须要执行CMD2
若真,则状态码变量 $? 返回0
若假,则状态码变量 $? 返回1
条件测试命令:
查看帮助
[root@centos8 data]# help [ [root@centos8 data]# help test 选项 -a FILE True if file exists. -b FILE True if file is block special. -c FILE True if file is character special. -d FILE True if file is a directory. -e FILE True if file exists. -f FILE True if file exists and is a regular file. -g FILE True if file is set-group-id. -h FILE True if file is a symbolic link. -L FILE True if file is a symbolic link. -k FILE True if file has its `sticky' bit set. -p FILE True if file is a named pipe. -r FILE True if file is readable by you. -s FILE True if file exists and is not empty. -S FILE True if file is a socket. -t FD True if FD is opened on a terminal. -u FILE True if the file is set-user-id. -w FILE True if the file is writable by you. -x FILE True if the file is executable by you. -O FILE True if the file is effectively owned by you. -G FILE True if the file is effectively owned by your group. -N FILE True if the file has been modified since it was last read. String operators: -z STRING True if string is empty. -n STRING STRING True if string is not empty. STRING1 = STRING2 True if the strings are equal. STRING1 != STRING2 True if the strings are not equal. STRING1 < STRING2 True if STRING1 sorts before STRING2 lexicographically. STRING1 > STRING2 True if STRING1 sorts after STRING2 lexicographically. Other operators: #变量测试 -o OPTION True if the shell option OPTION is enabled. -v VAR True if the shell variable VAR is set. -R VAR True if the shell variable VAR is set and is a name reference. ! EXPR True if expr is false. EXPR1 -a EXPR2 True if both expr1 AND expr2 are true. EXPR1 -o EXPR2 True if either expr1 OR expr2 is true. #数值测试 arg1 OP arg2 Arithmetic tests. OP is one of -eq, -ne, -lt, -le, -gt, or -ge. Arithmetic binary operators return true if ARG1 is equal, not-equal, less-than, less-than-or-equal, greater-than, or greater-than-or-equal than ARG2.
范例
#判断 NAME 变量是否认义 [ -v NAME ] #判断 NAME 变量是否认义而且是否引用 [ -R NAME ] [root@centos8 data]# echo $name [root@centos8 data]# [ -v name ] [root@centos8 data]# echo $? 1 [root@centos8 data]# name="xiaoming" [root@centos8 data]# [ -v name ] [root@centos8 data]# echo $? 0 [root@centos8 data]# [ -R name ] [root@centos8 data]# echo $? 1 [root@centos8 data]# [ -v name ] [root@centos8 data]# echo $? 0
范例
[root@centos8 data]# i=10;j=20; [root@centos8 data]# [ i -eq j ] -bash: [: i: integer expression expected [root@centos8 data]# [ $i -eq $j ] [root@centos8 data]# echo $? 1
范例
[root@centos8 data]# echo $name [root@centos8 data]# [ -z $name ] [root@centos8 data]# echo $? 0 [root@centos8 data]# unset name [root@centos8 data]# [ -z $name ] [root@centos8 data]# echo $? 0 [root@centos8 data]# name=xiaoming [root@centos8 data]# [ -z "$name" ] [root@centos8 data]# echo $? 1
[ ]用法
[[]] 用法,建议,当使用正则表达式或通配符使用,通常状况使用 [ ] == 左侧字符串是否和右侧的PATTERN相同 注意:此表达式用于[[ ]]中,PATTERN为通配符 =~ 左侧字符串是否可以被右侧的正则表达式的PATTERN所匹配 注意: 此表达式用于[[ ]]中;扩展的正则表达式
范例
[root@centos8 data]# NAME=linux [root@centos8 data]# [[ "$NAME" == linu\* ]] [root@centos8 data]# echo $? 1 [root@centos8 data]# [[ "$NAME" == linu* ]] [root@centos8 data]# echo $? 0 #结论:[[ == ]] == 右侧的 * 作为通配符,不要加“”,只想作为*, 须要加“” 或转义
范例
[root@centos8 data]# [ -a /data/test ] [root@centos8 data]# echo $? 0 [root@centos8 data]# ![ -a /data/test ] [ -a /data/test ] -a /data/test ] -bash: [: too many arguments [root@centos8 data]# ! [ -a /data/test ] [root@centos8 data]# echo $? 1 [root@centos8 data]# [ -w /etc/shadow ] [root@centos8 data]# echo $? 0
(CMD1;CMD2;...)和 { CMD1;CMD2;...; } 均可以将多个命令组合在一块儿,批量执行。使用man bash能够查看帮助
区别
( list ) 会开启子shell,而且list中变量赋值及内部命令执行后,将再也不影响后续的环境
{ list; } 不会启子shell, 在当前shell中运行,会影响当前shell环境
范例
[root@centos8 data]# echo $BASHPID 164220 [root@centos8 data]# ( echo $BASHPID;sleep 100) 164450 sshd(976)───sshd(164206)───sshd(164219)───bash(164220)─┬─bash(164449)───sleep(164450) [root@centos8 data]# echo $BASHPID 164220 [root@centos8 data]# { echo $BASHPID;} 16422
[ EXPRESSION1 -a EXPRESSION2 ] 而且,EXPRESSION1和EXPRESSION2都是真,结果才为真
[ EXPRESSION1 -o EXPRESSION2 ] 或者,EXPRESSION1和EXPRESSION2只要有一个真,结果就为 真
[ ! EXPRESSION ] 取反
范例
[root@centos8 data]# FILE=/data/test [root@centos8 data]# [ -f $FILE -a -x $FILE ] [root@centos8 data]# echo $? 1 [root@centos8 data]# chmod +x /data/test [root@centos8 data]# ll total 20 -rw-r--r-- 1 root root 0 Jan 9 22:28 a.log -rw-r--r-- 1 root root 181 Jan 4 18:29 arg.sh -rw-r--r-- 1 root root 1 Jan 6 19:17 lx.txt -rw-r--r-- 1 root root 116 Jan 5 15:50 rm.sh -rw-r--r-- 1 root root 403 Jan 2 17:39 systeminfo.sh -rwxr-xr-x 1 root root 110 Jan 3 10:17 test [root@centos8 data]# [ -f $FILE -a -x $FILE ] [root@centos8 data]# echo $? 0
COMMAND1 && COMMAND2 而且,短路与,表明条件性的AND THEN 若是COMMAND1 成功,将执行COMMAND2,不然,将不执行COMMAND2
COMMAND1 || COMMAND2 或者,短路或,表明条件性的OR ELSE 若是COMMAND1 成功,将不执行COMMAND2,不然,将执行COMMAND2
! COMMAND #非,取反
范例
[root@centos8 data]# test "A" = "B" && echo "string are equal" [root@centos8 data]# test "A" = "A" && echo "string are equal" string are equal [root@centos8 data]# ll -rw-r--r-- 1 root root 110 Jan 3 10:17 test.sh [root@centos8 data]# [ -f $FILE ] && [[ $FILE =~ \.sh$ ]] && chmod +x $FILE [root@centos8 data]# ll -rwxr-xr-x 1 root root 110 Jan 3 10:17 test.sh
&&与||组合使用
[root@centos8 data]# NAME=user;id $NAME && echo "$NAME is exist" || echo "$NAME is not exist" uid=1001(user) gid=1001(user) groups=1001(user) user is exist #注意:若是&& 和 || 混合使用,&& 要在前,|| 放在后。不然会出现逻辑错误
read:使用read来把输入值分配给一个或多个shell变量,read从标准输入中读取值,给每一个单词分配一个变 量,全部剩余单词都被分配给最后一个变量,若是变量名没有指定,默认标准输入的值赋值给系统内置 变量REPLY
read [options] [name ...]
经常使用选项
范例
[root@centos8 data]# read username [root@centos8 data]# echo $REPLY username [root@centos8 data]# read NAME SEX xiaoming boy [root@centos8 data]# echo $NAME $SEX xiaoming boy [root@centos8 data]# read -p "please input your name:" NAME please input your name:daxiong [root@centos8 data]# echo $NAME daxiong 面试题 read和输入重定向 [root@centos8 data]# echo 1 2 | read x y;echo $x $y [root@centos8 data]# echo 1 2 | (read x y;echo $x $y) 1 2 #Each command in a pipeline is executed as a separate process (i.e., in a subshell) #管道符把每一个命令执行都在独立的子进程中,因此第一种状况父进程没法读取子进程的变量
全局生效配置文件
/etc/profile /etc/profile.d/*.sh /etc/bashrc
我的用户生效配置文件
~/.bash_profile ~/.bashrc
配置文件加载顺序
/etc/profile.d/*.sh /etc/bashrc /etc/profile /etc/bashrc #此文件执行两次 .bashrc .bash_profile
配置文件加载顺序
/etc/profile.d/*.sh /etc/bashrc .bashrc
为交互式登陆的shell提供配置
全局:/etc/profile, /etc/profile.d/*.sh 我的:~/.bash_profile
用途:
1)用于定义环境变量
2)运行脚本或命令
为非交互式和交互式登陆的shell提供配置
全局:/etc/bashrc 我的:~/.bashrc
用途:
1)定义命令别名和函数
2)定义本地变量
格式
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
范例
#BMI指数 [root@centos8 script]# cat bmi.sh #!/bin/bash # #******************************************************************** #Author: yuanyuan #QQ: 1136132605 #Date: 2021-01-11 #FileName: bmi.sh #URL: http://www.bestvae.cn #Description: The test script #Copyright (C): 2021 All rights reserved #******************************************************************** read -p "请输入身高(单位m)" HIGH if [[ ! "$HIGH" =~ ^[0-2]\.?[0-9]{,2}$ ]];then echo "输入身高错误" exit 1 fi read -p "请输入体重(单位kg)" WEIGHT if [[ ! "$WEIGHT" =~ ^[0-9]{1,3}$ ]];then echo "输入体重错误" exit 1 fi BMI=`echo $WEIGHT/$HIGH^2|bc` if [ "$BMI" -le 18 ];then echo "你太瘦了多吃点" elif [ "$BMI" -lt 24 ];then echo "你的身材很棒" else echo "你太胖了,增强运动" fi
格式
case: case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac Execute commands based on pattern matching. #case支持全局通配符 *: 任意长度任意字符 ?: 任意单个字符 []:指定范围内的任意单个字符 |: 或,如 a或b
范例
#运维表 #!/bin/bash echo -en "\E[$[RANDOM%7+31];1m" cat <<EOF 1)备份数据库 2)清理日志 3)软件升级 4)软件回退 5)删库跑路 EOF echo -en '\E[0m' read -p "请输入上面的数字:" MENU if [[ ! "$MENU" =~ ^[1-5]$ ]];then echo "你的输入有误" exit 1 fi case $MENU in 1) echo "备份成功";; 2) echo "清理日志";; 3) echo "清理日志";; 4) echo "清理日志";; 5) echo "清理日志";; esac
练习
一、编写脚本 createuser.sh,实现以下功能:使用一个用户名作为参数,若是指定参数的用户存在,就 显示其存在,不然添加之。并设置初始密码为123456,显示添加的用户的id号等信息,在此新用户第一 次登陆时,会提示用户当即改密码,若是没有参数,就提示:请输入用户名
[root@centos8 script]# cat creatuser.sh #!/bin/bash if [ -z "$1" ];then echo "请输入用户名字格式为$0 username" exit 1 else getent passwd $1 > /dev/null if [ "$?" -eq 0 ];then echo "$1 is exist" echo `getent passwd $1` exit 1 else useradd $1 echo '123456' | passwd --stdin $1 > /dev/null passwd -e $1 > /dev/null echo -e "$1用户建立成功初始密码为123456\n`getent passwd $1`" fi fi
二、编写生成脚本基本格式的脚本,包括做者,联系方式,版本,时间,描述等
[root@centos8 script]# cat /root/.vimrc set ts=4 set expandtab set ignorecase set cursorline set autoindent set showcmd autocmd BufNewFile *.sh exec ":call SetTitle()" func SetTitle() if expand("%:e") == 'sh' call setline(1,"#!/bin/bash") call setline(2,"#") call setline(3,"#********************************************************************") call setline(4,"#Author: yuanyuan") call setline(5,"#QQ: 1136132605") call setline(6,"#Date: ".strftime("%Y-%m-%d")) call setline(7,"#FileName: ".expand("%")) call setline(8,"#URL: http://www.bestvae.cn") call setline(9,"#Description: The test script") call setline(10,"#Copyright (C): ".strftime("%Y")." All rights reserved") call setline(11,"#********************************************************************") call setline(12,"") endif endfunc autocmd BufNewFile * normal G