命令替换
方法一
`command`
复制代码
方法二
$(command)
复制代码
案列
获取所用用户并输出
#!/bin/bash
index = 1
for user in `cat /etc/passwd | cut -d ":" -f 1`
do
echo "this is $index user : $user"
index=$(($index + 1))
done
复制代码
根据系统时间计算明年
#!/bin/bash
echo "This Year is $(date +%Y)"
echo "Next Year is $(($(date +%Y) + 1))"
复制代码
算数运算
- 使用$(( 算数表达式 ))
- 其中若是用到变量能够加$ 也能够省略
- 如:
#!/bin/bash
num1=12
num2=232
echo $(($num1 + $num2))
echo $((num1 + num2))
echo $(((num1 + num2) * 2))
复制代码
案列
根据系统时间获取今年还剩多少个星期,已通过了多少个星期
#!/bin/bash
days=`date +%j`
echo "This year have passed $days days."
echo "This year have passed $(($days / 7)) weeks."
echo "There $((365 - $days)) days before new year."
echo "There $(((365 - $days) / 7)) weeks before new year."
复制代码
判断nginx是否运行,若是不在运行则启动
#!/bin/bash
nginx_process_num=`ps -ef | grep nginx | grep -v grep | wc -l`
echo "nginx process num : $nginx_process_num"
if [ "$nginx_process_num" -eq 0 ]; then
echo "start nginx."
systemctl start nginx
fi
复制代码
++ 和 -- 运算符
num=0
echo $((num++))
echo $((num))
复制代码
有类型变量
- shell是弱类型变量
- 可是shell能够对变量进行类型声明
declare和typeset命令
- declare命令和typeset命令二者等价
- declare、typeset命令都是用来定义变量类型的
declare 参数列表
- -r 只读
- -i 整型
- -a 数组
- -f 显示此脚本前定义过的全部函数及内容
- -F 仅显示此脚本前定义过的函数名
- -x 将变量声明为环境变量
经常使用操做
num1=10
num2=$num1+10
echo $num2
expr $num1 + 10
declare -i num3
num3=$num1+90
echo $num3
declare -f
declare -f
declare -a array
array=("aa" "bbbb" "ccccc" "d")
echo ${array[@]}
echo ${array[2]}
echo ${#array[@]}
echo ${#array[3]}
array[0]="aaa"
unset array[2]
echo ${array[@]}
unset array
echo ${array[@]}
array=("aa" "bbbb" "ccccc" "d")
echo ${array[@]:1:4}
for v in ${array[@]}
do
echo $v
done
env="environment"
declare -x env
echo ${env}
复制代码