命令替换:
方法一:`command`
方法二:$(command)
例子1:
获取系统所有用户并输出
#!/bin/sh
index=1
for user in `cat /etc/passwd | cut -d ":" -f 1`
do
echo "This is $index user: $user"
index=$(($index+1))
done例子2:
根据系统时间计算今年或明年
echo "This is $(($(date +%Y) + 1)) year"
date +"%Y-%m-%d %H:%M:%S"
例子3:
根据系统时间获取今年还剩多少个星期,已经过了多少个星期
echo $(($(date +%j)/7)) --已经过了多少个星期
echo $(((365-$(date +%j))/7)) --还剩多少个星期
例子4:
判断nginx进程是否存在,若不存在则自动拉起
#!/bin/sh
nginx=$(ps -ef|grep nginx|grep -v grep|wc -l)
if [ $nginx -eq 0 ];then
systemctl start nginx
fi
总结:``和$()是等价的
$(())主要用来进行整数计算,包括加减乘除
$(((100+30)/13))
有类型变量总结:
1、declare -r #声明变量为只读类型
2、declare -i #声明变量类型为整型
3、declare -f #在脚本中显示定义的函数和内容
4、declare -F #在脚本中显示定义的函数
5、declare -a
arrary=("jones" "mike" "kobe" "jordan")
输出数组内容:
echo ${arrary[@]} 输出全部内容
echo ${arrary[1]} 输出下标索引为1的内容
获取数组长度:
echo ${#arrary} 数组内元素个数
echo ${#arrary[2]} 数组内下标为索引为2的元素长度
给数组某个下标赋值:
arrary[0]="lily"
arrary[20]="kobe"
数组遍历:
for v in ${arrary[@]}
do
echo $v
done
6、declare -x #声明为环境变量