[英]Linux Bash - Comparing two variables in an if statement
我正在嘗試執行變量交換,其中用戶輸入2個不同的數字,並執行檢查以確保第二個數字“結束”大於第一個數字“開始”。 如果起始編號大於終止編號,它將進行交換,以便以后的計算有效。
我得到的錯誤是:./Boot.sh:94行:[:-ne:一元運算符應為
if [ $end -gt $start ]
then
start=$swapper
end=$start
swapper=$end
fi
這是完整的代碼,因為我似乎在注釋中犯了一些錯誤,我剛剛嘗試了雙括號,但仍然遇到相同的錯誤。
{
counter=0
while :
do
if [ $counter -gt '0' ]
then
printf "\nWould you like to continue terminating processes?\n"
echo "Type 1 to contiue or 0 to exit"
read endProgram
if [ $endProgram -ne '1' ]
then
break
fi
fi
echo "Welcome to Max process killer"
while :
do
echo "Enter the first number of the process range"
read start
echo "Enter the last number of the process range"
read end
if [ $start -le '3' -o $end -le '3' ]
then
echo "Your first and last pid IDs must be geater then 3"
read -n 1
break
if [[ $end -gt $start ]]
then
start=$swapper
end=$start
swapper=$end
fi
fi
printf "\nAre you sure you would like to terminate these processes?\n"
echo "Enter 1 to confirm or 0 to cancel"
read confirm
if [ $read -ne '1' ]
then
break
fi
while [ $start -le $end ]
do
kill -9 "$start"
echo "Process ID:"$start "has been terminated"
start=$(( $start + 1 ))
done
break
done
counter=$(($counter + 1))
done
}
您的代碼:
read confirm
if [ $read -ne '1' ]
您將輸入讀為變量confirm
而不是變量read
。 變量read
為空,您將收到錯誤:
./Boot.sh: line 94: [: -ne: unary operator expected
提示:使用默認值(例如0)避免空變量:
if [ "${confirm:-0}" -ne '1' ]
來自man bash:
${parameter:-word}
:使用默認值。 如果參數未設置或為null,則替換單詞的擴展名。 否則,將替換參數的值。
${parameter:=word}
:分配默認值。 如果參數未設置或為空,則將單詞擴展指定給參數。 然后替換參數的值。 不能以此方式分配位置參數和特殊參數。
嘗試使用雙括號。 它們通常更安全。 這是一個比較[[]]
和[]
的不錯的Wiki頁面 。
if [[ $end -gt $start ]]
then
swapper=$start
start=$end
end=$swapper
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.