shell学习 命令替换

命令替换

               语法格式
方法一          `command`
方法二          $(command)

例子1:
   获取系统得所有用户输出

   cat /etc/passwd

   cat /etc/passwd | cut -d ":" -f 1

   指定:为分隔符,回去第一行

   脚本:
   #!/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

例子2:
    根据系统时间计算今年或明年

    echo "This is $(date +%Y) year"

    echo "This is $(($(date +%Y) + 1))"

例子3:根据系统时间获取今年还剩下多少星期,已经过了多少星期

    date +%j

    echo "this is have passed $(date +%j) $days"
    echo "this is have passed $(($(date +%j) / 7)) weeks"

    echo "There is $(((365 - $(date +%j)) / 7)) days before new year"

列子4:

    判定nginx进程是否存在,若不存在则自动拉起该进程

    #/bin/bash
    #

    nginx_process_num=$(ps -ef | grep nginx | grep -v grep | wc -l)

    if [ $nginx_process_num -eq 0 ];then
       /usr/local/nginx/sbin/nginx
    fi

总结:`` 和 $()两者等价的,但是推荐初学者使用$(),易于掌握,缺点是在极少的unix可能不支持,但是 `` 是支持 的

     $(()) 主要是来计算整数运算的,包括加减乘除,引用变量前面可以加 $, 也可以不加 $

     $(( (100 + 30) / 13))

     num1=20;num2=30
     ((num++))
     ((num--))
     $(($num1+$num2*2))

你可能感兴趣的:(shell)