您的位置:首页 > 运维架构 > Shell

Shell笔记1-命令替换

2020-08-08 19:12 721 查看

命令替换

命令替换:将命令的输出结果作为值赋给某个变量

  1. `command`

    例:

    获取系统得所有用户并输出

    #cut--切割 -d 根据 -f 取第几列
    ~$ 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. $(command)

    例:

    系统计算今年或明年时间

    ~$ date
    2020年 8月 8日 星期六 17时48分24秒 CST
    ~$ date +%Y
    2020
    ~$ echo "This is $(date +%Y) year"
    This is 2020 year
    #$()--命令替换  $(())--算数运算
    ~$ echo "This is $(($(date +%Y)+1)) year"
    This is 2021 year
    #shell语法并不严谨
    ~$ num1=90
    ~$ num2=30
    ~$ echo "$((num1+num2))"
    120
    ~$ echo "$(($num1+$num2))"

    练习:

    (1)根据系统时间获取今年还剩下多少星期,已经过了多少星期

    #今年过了多少天
    ~$ date +%j
    221
    #已经过了多少星期
    ~$ echo "This year have passed $(($(date +%j)/7))"
    This year have passed 31
    #还有多少天和星期过新年
    ~$ echo "This is $((365-$(date +%j))) day before new year"
    This is 144 day before new year
    ~$ echo "This is $(((365-$(date +%j))/7)) week before new year"
    This is 20 week before new year

    (2)判断 nginx 进程是否启动,如果没启动,则启动

    #!bin/bash
    
    # 判断 ngnix进程是否启动,如果没有启动,则启动
    
    # grep -v grep 是过滤掉grep nginx这个进程
    # wc -l 是统计输出多少行
    nginx_process_num=$(ps -ef | grep nginx | grep -v grep | wc -l)
    
    if [ $nginx_process_num -eq 0 ]; then
    systemctl start nginx
    fi

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: