系统变量
$HOME、$PWD、$SHELL、$USER等
自定义变量
定义: 变量=值
撤销变量 unset 变量
静态变量 readonly ,不能unset
定义规则
特殊变量
$n
n为数字,$0表示该脚本的名称.$1 $2 $3....$9 表示第一到九个变量,10以上要这样写 ${11}
$#
可以获取参数的个数
$* $@
$* (功能描述:这个变量代表命令行中所有的参数,$*把所有的参数看成一个整体)
$@ (功能描述:这个变量也代表命令行中所有的参数,不过$@把每个参数区分对待)
$?
查看最后一次执行的命令的返回状态.如果正确的话是0 ,非0 就不正确
例如:
[root@hadoop101 datas]# S=$[(2+3)*4]
[root@hadoop101 datas]# echo $S
[ condition ] condition前后要有空格
条件非空即为true ,例如[ atguigu ]返回true ,[]返回false
两个整数之间的比较
按照文件权限进行判断
按照文件类型进行判断
(1)23是否大于等于22
[root@hadoop101 datas]$ [ 23 -ge 22 ]
[root@hadoop101 datas]$ echo $?
0
(2)helloworld.sh是否具有写权限
[root@hadoop101 datas]$ [ -w helloworld.sh ]
[root@hadoop101 datas]$ echo $?
0
(3)/home/atguigu/cls.txt目录中的文件是否存在
[root@hadoop101 datas]$ [ -e /home/atguigu/cls.txt ]
[root@hadoop101 datas]$ echo $?
1
(4)多条件判断(&& 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一条命令执行失败后,才执行下一条命令)
[root@hadoop101 ~]$ [ condition ] && echo OK || echo notok
OK
[root@hadoop101 datas]$ [ condition ] && [ ] || echo notok
notok
语法
单分支
if [ 条件判断式 ];then
程序
fi
或者
if [ 条件判断式 ]
then
程序
fi
多分支
if [ 条件判断式 ]
then
程序
elif [ 条件判断式 ]
then
程序
else
程序
fi
注意事项:
(1)[ 条件判断式 ],中括号和条件判断式之间必须有空格
(2)if后要有空格
语法
case $变量名 in
"值1")
如果变量的值等于值1,则执行程序1
;;
"值2")
如果变量的值等于值2,则执行程序2
;;
…省略其他分支…
*)
如果变量的值都不是以上的值,则执行此程序
;;
esac
注意事项:
(1)case行尾必须为单词“in”,每一个模式匹配必须以右括号“)”结束。
(2)双分号“;;”表示命令序列结束,相当于java中的break。
(3)最后的“*)”表示默认模式,相当于java中的default。
第一种
for (( 初始值;循环控制条件;变量变化 ))
do
程序
done
第二种
for 变量 in 值1 值2 值3…
do
程序
done
while [ 条件判断式 ]
do
程序
done
read(选项)(参数)
选项:
-p:指定读取值时的提示符;
-t:指定读取值时等待的时间(秒)。
参数
变量:指定读取值的变量名
例如:
提示7秒内,读取控制台输入的名称
[root@hadoop101 datas]$ touch read.sh
[root@hadoop101 datas]$ vim read.sh
#!/bin/bash
read -t 7 -p "Enter your name in 7 seconds " NAME
echo $NAME
[root@hadoop101 datas]$ ./read.sh
Enter your name in 7 seconds xiaoze
xiaoze
basename
语法
basename [string / pathname] [suffix] (功能描述:basename命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来。
选项:
suffix为后缀,如果suffix被指定了,basename会将pathname或string中的suffix去掉。
截取该/home/atguigu/banzhang.txt路径的文件名称
[root@hadoop101 datas]$ basename /home/atguigu/banzhang.txt
banzhang.txt
[root@hadoop101 datas]$ basename /home/atguigu/banzhang.txt .txt
banzhang
dirname
语法
dirname 文件绝对路径 (功能描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分))
获取banzhang.txt文件的路径
[root@hadoop101 ~]$ dirname /home/atguigu/banzhang.txt
/home/atguigu
语法:
[ function ] funname[()]
{
Action;
[return int;]
}
funname
注意
必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译。
函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)
例如,,计算两个输入参数的和
[root@hadoop101 datas]$ touch fun.sh
[root@hadoop101 datas]$ vim fun.sh
#!/bin/bash
function sum()
{
s=0
s=$[ $1 + $2 ]
echo "$s"
}
read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;
[root@hadoop101 datas]$ chmod 777 fun.sh
[root@hadoop101 datas]$ ./fun.sh
Please input the number1: 2
Please input the number2: 5
7
原文:https://www.cnblogs.com/earnest-jie/p/12877716.html