1

Here is what I tried doing:

#!/bin/sh
res=`df | awk 'FNR == 2 { print $5 }'`
res2=$((res+0))

Here is my error:

-bash: 53%: syntax error: operand expected (error token is "%")

I Googled 'string to int bash' which showed me $((res+0)) but it doesn't work due to the % in the string (53%). How do I convert it in such a way I can do an if statement such as the one below (but that works)?

if [ "$res2" -ge 50 ]
then
    echo "Your disk >=50% full!"
fi
1

Let awk do it:

df -P | awk 'NR == 2 { print $5+0; exit }'
  • 1
    Nice! Like bash, awk also stores even numerical values as strings. But this works because when a variable is used in a numerical context, awk strips off any trailing non-numerical junk. (It would also strip off any leading spaces, if $5 happened to contain some. When you use the default field-separation, though, $5 won't.) – dubiousjim Sep 24 '12 at 6:59
2

Just tell awk to suppress the %:

#!/bin/sh
res=`df | awk 'FNR == 2 { sub("%","",$5); print $5 }'`
res2=$((res+0))

But I don't see that the res2 line does anything. Unless you have declare -i res2, bash is still going to treat it as a string. You can do the following just fine:

if [ $res -ge 50 ]; then
    echo "Your disk >= 50% full!"
fi
2

A little variable manipulation would also do:

res=`df | awk 'FNR == 2 { print $5 }'`
limit=50

if ((  ${res%\%} > limit )); then
    echo "Your disk >= ${limit}% full"
fi

${res%\%} will remove the last occurrence of % from res, (the first % means remove last occurrence and then you need to escape \% to say that's the pattern to be removed)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy