2016-07-15 72 views
0

條件,我在linux工作的一些bash腳本,我只是想比較兩個數的整數。一個是磁盤大小,另一個是限制。我如何使用Linux cmd,然後如下圖所示將其存儲在一個變量獲得磁盤大小,比較使用IF在bash腳本

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 

上運行,我得到了以下錯誤:

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

這是你跑了確切的代碼?不像你已經越過第二行 – Fazlin

+0

你'df'線看起來不錯,我可以從我的測試結果確認你確定你沒有圍繞'='原代碼空間。 – sjsam

+0

爲什麼無法複製和粘貼實際的代碼? – sjsam

回答

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

應該

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

另外

limit = 80 

應該

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

旁註:檢查[ command substitution ]和使用[ shellcheck ]檢查腳本發出

+0

實際上沒有空間我貼在這裏錯誤地現在我改變了達,但即使即時即時得到相同的錯誤。相反,比較變量,如果我通過整數條件工作就像如果[80 -eq 80]這對我工作正常 – Gan

+0

@甘:其實你可能有其他問題與腳本,檢查編輯的答案,並窺視給出的鏈接注意:) – sjsam

0

在bash,沒有必要使用它之前聲明變量,你可以聲明並即時賦值,所以第一行(declare -i)可以被刪除。

如果你想使用的百分比,「DF」有一個選項可以做到這一點(更多信息曼DF)。 ,經過與「grep」可以,你可以只與正則表達式的數量,注意我用的只有兩個命令對應您在第一種方法使用而不是三個。

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

此外,用於捕獲命令的輸出,並把一個變量的使用的內部:

var1=$(put your command with params here) 

因此,第一行是:

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

在bash,有在等號,變量名稱和賦值之間不能有空格。

limit=80 

最後,比較整數使用雙括號和變量,而「$」作比較,而不是雙括號。

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

您可以使用比較:

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

如果你想嚴格等於:...((output == limit))... –

+0

原始方法btw有沒有問題? – sjsam

+0

用於比較整數的用法:((var1 == value)),詳細信息請見:http://mywiki.wooledge.org/BashGuide。此外,請刪除以下空格:限制= 80 –