Gan
Gan

Reputation: 93

Comparing the integer using IF condition in bash script

I'm working on some bash script in linux i just want to compare two number. One is disk size and another one is limit. I get the disk size by using linux cmd and store it in a variable as shown below,

declare -i output    
output= df -h | grep /beep/data| awk '{ printf ("%d",$5)}'    
echo "$output" # Got 80 here

limit = 80


if  [ $output -eq $limit ];
then
fi

On running I got the below error:

line 27: [: -eq: unary operator expected"

Upvotes: 0

Views: 4335

Answers (2)

Manuel Alcocer
Manuel Alcocer

Reputation: 131

In BASH, it is unnecessary to declare variables before using it, you can declare and assign values on the fly, so the first line (declare -i) can be removed.

If you want to get the used percent, 'df' has an option to do that (man df for more info). After, with 'grep', you can get only the number with that regexp, note I use only two comands instead three you use in your first approach.

$ df --output=pcent /beep/data | grep -Eo '[0-9]+'

Also, for catching the output of a command and put inside of a variable use:

var1=$(put your command with params here)

Therefore, the first line would be:

output=$(df --output=pcent /beep/data | grep -Eo '[0-9]+')
echo "${output}"

In BASH, there can be no spaces between the equal symbol, the name of the variable and the assigned value.

limit=80

Finally, for comparing integers use double parenthesis and variables without '$' to make the comparison, instead double brackets.

if (( output >= limit )); then
    echo 'output is greater or equal than limit'
fi

You can use for comparing:

==  Equal to
!=  Not equal
>   Greater than
<   Less than
>=  Greater or equal
<=  Less or equal

Upvotes: 3

sjsam
sjsam

Reputation: 21955

output= df -h | grep /beep/data| awk '{ printf ("%d",$5)}'    

should be

output="$(df -h | grep /beep/data| awk '{ printf ("%d",$5)}')"
#Used command substitution in the previous step

Also

limit = 80

should be

limit=80 # no spaces around =, check all your variables for this

Sidenote:Check [ command substitution ] and use [ shellcheck ] to check script issues

Upvotes: 4

Related Questions