Shell Snippet

  1. 显示当前时间+时区
echo `date +"%Y-%m-%d %H:%M:%S.%N"|cut -b1-23``date +"%:z"`
# 输出 2017-04-07 10:41:27.783+08:00
  1. 提示输入确认信息
# 30s 等待时间
read -t 30 -p "Upgrade operation will interrupt the network service. Stop or migrate virtual machines first. The system will upgrade the vSwitch. Continue? [Y/N]:"
  1. switch-case语法
read reply
case $reply in
    Y | y)  echo "yes" ;;
    N | n)  echo "no" ;;
    *    )  echo "Input error" ;;
esac
  1. 读取键盘输入
read type
if [ "$type" = 'yes' ]
then
    echo "xxx"
elif [ "$type" != 'no' ]
then
    echo "xxx"
fi
  1. 循环语句
# a. for
for item in xxx; do
    echo "$item"
done
# b. while
while [ condition ]; do
    echo ""
done 
# c. until
until condition
do
    echo "xxx"
done
  1. and , or
[ condition1 && condition2 && ..]
[ condition1 || condition2 || ..]
  1. 字符串操作
比较:
if [ $str1 = $str2 ]  # ==
if [ $str1 != $str2 ]   # !=
if [ $str1 =~ $str2 ]  # str1 包含 str2
切片:
string=abcdefg
${string:0:3} # 截取从0位置开始,长度为3的字符串,abc
${string:0:-2} # 截取从0位置开始,到倒数第3个字符,abcde
${string:2}  #  截取从2位置开始,一直到最后,cdefg
${string:0-4:3}  #  截取从倒数第4位置开始,长度为3的字符串,def
${string:$((-2))} # 截取从倒数第2位置,一直到最后 fg
${string:0-2} # 同上
  1. 数组操作
// 1. 声明数组:
arr=(1 2 3 4)  
arr=([0]=1 [1]=2 [2]=3)
// 2. 遍历数组:
for item in ${arr[*]}; do
    echo $item;
done
//3. 追加数组:
a. arr=(${arr[*]} 5)
b. arr+=(6)
// 4. 删除数组元素
unset arr[0]
//5. 数组长度:
echo ${#array[*]}  或者 echo ${#arr[@]}
//6. 数组切片
echo ${arr[@]:0:2}
  1. shell脚本执行的参数
命令行参数              set选项                            说明
sh -n 
                    
                    

你可能感兴趣的:(Shell Snippet)