====================
bash
shell脚本:把平时在命令行执行的命令放在一个文本文件内,此文件即shell脚本
注意:绝大部分是非交互式命令
执行脚本
# bash 脚本文件
# ./脚本文件
# 路径/脚本文件
交互式
命令敲完回车之后没有直接出结果,并且需要在输入其他内容的命令
[root@web tmp]# passwd w
Changing password for user w.
New password:
BAD PASSWORD: The password is a palindrome
Retype new password:
passwd: all authentication tokens updated successfully.
非交互式
命令敲完回车之后直接出结果
[root@web tmp]# echo 1 | passwd --stdin w
Changing password for user w.
passwd: all authentication tokens updated successfully.
变量
变量名称=值
变量名称命名规定:只能由数字字母和下滑线组成,不能以数字开头
变量的调用:
$变量名称
如果变量名称边界线不明,需要加{}来区分:
# echo ${n}um
变量类型不需要定义,变量默认值可以是0或者空字符串
[root@web tmp]# a=8
[root@web tmp]# echo $abc
[root@web tmp]# echo ${abc}A
A
[root@web tmp]# echo $[${abc}+8]
8
随机数变量
# echo $RANDOM
取消屏幕回显
#stty -echo
恢复屏幕回显
#stty echo
取1-10随机数
# echo [$RANDOM%10+1]
test命令详解
可以用[]代替
[ 5 -gt 3 ]
数值比较
-gt > greater than
-lt < less than
-ge >= greater than or equal
-le <= less than or equal
-ne != not equal
-eq = equal
字符串比较
== 或者 =
!=
[root@web tmp]# a="/etc/passwd"
[root@web tmp]# if [ $a == "/etc/passwd" ];then echo hello; fi
hello
[root@web tmp]# if [ $a = "/etc/passwd" ];then echo hello; fi
hello
文件比较
-e exsit
[root@web tmp]# if [ -e $a ];then echo hello; fi
hello
[root@web tmp]# a="/etc/pas"
[root@web tmp]# if [ -e $a ];then echo hello; fi
if判断
单条件判断
if 命令;then
命令1
命令2
命令3
...
fi
if 命令;then
命令1
命令2
命令3
...
else
命令
fi
多条件判断
if 命令;then
命令1
命令2
elif 命令;then
命令1
elif 命令;then
命令1
else
命令
fi
多条件判断
case $i in
1)
命令
命令
;;
2)
命令
命令;;
3)
命令
命令;;
*)
命令
命令
esac
[root@web tmp]# a=8
[root@web tmp]# case $a in
> 2)
> echo hello
> ;;
> "abc") echo haha
> ;;
> 8) echo 就是他;;
> *)
> echo 你写错了
> esac
就是他
布尔值
0 1
==================
标准输出 &
标准正确 1
执行命令所得正确结果
标准错误 2
执行命令所得非正确结果
标准输入 0
[root@web tmp]# echo hello
hello
[root@web tmp]# echo hello 1>/dev/null
[root@web tmp]# ecfd hello 1>/dev/null
bash: ecfd: command not found...
[root@web tmp]# ecfd hello 2>/dev/null
[root@web tmp]# ecfd hello &>/dev/null
[root@web tmp]# echo hello &>/dev/null
[root@web tmp]# if ls &>/dev/null;then echo hello; fi
hello
[root@web tmp]# if pwd &>/dev/null;then echo hello; fi
hello
获取上一条命令的返回值
使用$?
例子:
[root@web tmp]# grep hello /etc/passwd
[root@web tmp]# echo $?
1
[root@web tmp]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@web tmp]# echo $?
0
======================
3133

被折叠的 条评论
为什么被折叠?



