- shell脚本if判断变量介绍
(16条消息) shell脚本中if判断‘-a‘ - ‘-z‘含义_shell if -a_早九晚十二的博客-CSDN博客
1.判断参数是否存在,有输出绿色ok,无就输出红色failed
# echo -e "\033[字背景颜色;字体颜色;字体属性m 需要输出的内容 \033[0m"
\033 转义起始符,定义一个转义序列,也可以使用 \e 或 \E 代替。
[ 表示开始定义颜色。
字背景颜色 范围 40-47 。
字体颜色 范围 30-37 。
黑底彩色:90-97 。
0默认,30黑,31红,32绿,33黄色,34蓝色,35紫色,35青色,37白色
m 转义终止符,表示颜色定义完毕。
再次使用 \033[ ,表示再次开启颜色定义,0 表示颜色定义结束,所以 \033[0m 的作用是恢复之前的配色方案。
[root@localhost she]# vim iscolor.sh
#!/bin/sh
iscolor(){
if [ $# -ne 0 ]
then
echo -e "\e[32m ok \e[0m"
else
echo -e "\e[31m failed \e[0m"
fi
}
read -p ”input:“ num
iscolor $num
2.判断有无位置参数
-z 检测字符串长度是否为0,为0返回 true。 [ -z $a ] 返回 false。
-n 检测字符串长度是否不为 0,不为 0 返回 true。 [ -n "$a" ] 返回 true。
[root@localhost she]# vim isset.sh
#!/bin/sh
isset(){
if [ ! -z $1 ]
then
echo -e "$1"
else
echo -e "无参:error"
fi
}
isset $1
3.判断俩个变量的大小
gt大于、eq等于、ge大于等于、lt小于、le小于等于、ne不等于
[root@localhost she]# vim ismax.sh
ismax(){
if [ $a -gt $b ]
then
echo -e "$a"
elif [ $a -eq $b ];then
echo -e "$a 等于 $b"
else
echo -e "$b"
fi
}
read -p "input:" a b
ismax $a $b
4.把密码文件按行赋值到数组中
#awk 每行按空格或TAB分割,输出文本
[root@localhost she]# ARRAY=($(awk '{print $0}' /etc/passwd))
[root@localhost she]# echo ${ARRAY[0]}
5.使用关联数组统计密码文件中用户使用的不同类型shell的数量
Bash 支持关联数组,可以使用任意的字符串、或者整数作为下标来访问数组元素。
关联数组使用 declare 命令来声明,语法格式如下:
declare -A array_nameRS:Record Separator,记录分隔符
ORS:Output Record Separate,输出当前记录分隔符
FS:Field Separator,字段分隔符
OFS:Out of Field Separator,输出字段分隔符
declare -a array_1=( `awk 'BEGIN{ FS=":"; ORS=" " }{ print $7 } ' /etc/passwd` )
declare -A array_2
for i in ${array_1[*]}
do
let array_2[$i]++
done
for j in ${!array_2[@]}
do
echo $j : ${array_2[$j]}
done
6.使用关联数组按扩展名统计指定目录中文件的数量
declare -a array_1=`ls`
declare -A array_2
for i in ${array_1[@]}
do
let array_2[${i#*.}]++
done
for j in ${!array_2[@]}
do
echo $j : ${array_2[$j]}
done
7.你需要打印一个给定的数字的反序,例如输入1234,输出4321,如果没有输入数据,应该抛出错误和使用脚本说明。
- n % 10, 将得到余数
- 把最后的数先存到rev中,最后顺序读取
#!/bin/bash
if [ $# -eq 0 ]; then
echo "error:not input number!"
echo "please input $0 number!"
exit 1
fi
num=$1
rev=()
x=0
while [ $num -gt 0 ]
do
x=$(( $num % 10 ))
rev+=($x)
num=$(( $num/10 ))
done
echo "${rev[*]}" | tr -d ' '
8.写出SHELL函数RevertInput,函数必须获取三个参数,然后将三个参数倒序echo打印出来,函数必须检查参数个数的合法性,
如果参数非法,打印”Illegal parameters”,
对于下面的输入: RevertInput “this is para1” para2 para3
应该输出:
para3
para2
this is para1
#!/bin/bash
RevertInput() {
if [ "$#" -ne 3 ]; then
echo "Illegal parameters"
else
echo "$3 $2 $1"
fi
}
RevertInput "this is para1" para2 para3
9.判断奇数偶数
is_12(){
if (( $num%2 == 0 ))
then
echo '偶数'
else
echo '奇数'
fi
}
read -p "input:" num
is_12 $num
10.打印*
read -p 'input:' num
for ((i=1;i<=$num;i++))
do
for ((j=1;j<=$i;j++))
do
echo -n '* '
done
echo ' '
done