Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
add comment

3 Answers 3

up vote 2 down vote accepted

Let awk do it:

df | awk 'NR == 2 { print $5+0; exit }'
share|improve this answer
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
add comment

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
share|improve this answer
add comment

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)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.