Assing a variable and use it inside of if statement shell scripting

后端 未结 2 1064
囚心锁ツ
囚心锁ツ 2021-01-20 14:08

I am new to shell scripting and trying to make a few small scripts. I got stuck when i tried to write if condition. In the code below i am trying to get the $5 value from df

2条回答
  •  -上瘾入骨i
    2021-01-20 15:11

    Let's see what shellcheck.net has to tell us:

    Line 1:
      #!/bin/sh
    ^-- SC1114: Remove leading spaces before the shebang.
    
    Line 3:
    temp = $(df -h | awk '$NF=="/"{$5}')
         ^-- SC1068: Don't put spaces around the = in assignments.
    
    Line 4:
    if [ $temp > 0 ] ; then
         ^-- SC2086: Double quote to prevent globbing and word splitting.
               ^-- SC2071: > is for string comparisons. Use -gt instead.
               ^-- SC2039: In POSIX sh, lexicographical > is undefined.
    

    Um, ok, after a little fixing:

    #!/bin/sh
    temp=$(df -h | awk '$NF=="/"{$5}')
    if [ "$temp" -gt 0 ] ; then  
       df -h | awk '$NF=="/" {printf("%s\n"),$5}'
       (date -d "today" +"Date:%Y.%m.%d"" Hour: %H:%M")
    fi
    

    The [ ... ] command is the same as test command. Test does not have < comparison for numbers. It has -gt (greater then). See man test.
    This will run now, but definitely not do what you want. You want the fifth column of df output, ie. the use percents. Why do you need -h/human readable output? We dont need that. Which row of df output do you want? I guess you don't want the header, ie. the first row: Filesystem 1K-blocks Used Available Use% Mounted on. Let's filter the columns with the disc name, I choose /dev/sda2. We can filter the row that has the first word equal to /dev/sda2 with grep "^/dev/sda2 ". The we need to get the value on the fifth column with awk '{print $5}'. We need to get rid of the '%' sign too, otherwise shell will not interpret the value as a number, with sed 's/%//' or better with tr -d '%'. Specifying date -d"today" is the same as just date. Enclosing a command in (...) runs it in subshell, we don't need that.

    #!/bin/sh
    temp=$(df | grep "^/dev/sda2 " | awk '{print $5}' | tr -d '%')
    if [ "$temp" -gt 0 ]; then  
       echo "${temp}%"
       date +"Date:%Y.%m.%d Hour: %H:%M"
    fi
    

    This is a simple, that if use percentage on disc /dev/sda2 is higher then 0, then it will print the use percentage and print current date and time in a custom format.

提交回复
热议问题