whileループの中で、値に応じて異なる変数や配列に格納する処理を行っていますが、数字一文字3の場合だけ特別に追加処理が必要なため一旦最初のIF文では全ての数字を配列に格納した後、次のELIFの処理にて最初のIF文で格納した配列の最後の要素をチェックさせその数字が3であった場合は別処理用の別変数と別配列に格納する処理を行いたいと思っておりますが以下のエラーが発生してしまいます(比較演算子を-eq, =としても結果は同じ)。上手く配列の最後の要素を参照する方法をご存知の方、ご教授の程よろしくお願いいたします。
cal.sh: line 17: [: =: unary operator expected
cal.sh: command substitution: line 20: syntax error: unexpected end of file
入力するテキストファイルresult.logには以下のようにランダムな数字が並び、最後の行に3があります。
53
219
3
rfile='/Backup/monitor/result.log' declare -a r_count=() declare -a no_eps=() cnt=0 r_chk=0 while read line || [ -n "${line}" ]; do if [ `(echo "${line}" | grep -o '^[0-9]*$')` ];then cnt=`expr "${cnt}" + 1` r_count+=("$line") line17: elif [ `(echo "${r_count[@]}" |awk '{print $(NF)}')` = 3 ];then r_chk=`expr "${r_chk}" + 1` r_host=`(echo "${line}" |awk '{print $6}'` no_eps+=("$r_host") fi done < $rfile
あちこちマスクしていますが、修正版のスクリプトです。
#!/bin/bash rfile='/Backup/result.log' declare -a count=() declare -a lost_rs=() declare -a no_ps=() declare -a all_host=() cnt=0 cnt1=0 r_chk=0 while read line || [ -n "${line}" ]; do if [ `(echo "${line}" |grep -o 'IP')` ];then aep=`(echo "${line}" |awk -F ' ' '{print $2}' )` all_host+=("${aep}") fi if [ `(echo "${line}" | grep -o '^[0-9]*$')` ];then cnt=`expr "${cnt}" + 1` rpl_count+=("${line}") mng=`echo ${count[${#count[@]}-1]}` elif [ `(echo "${line}" | grep -o 'SSH')` ];then cnt1=`expr "${cnt1}" + 1` line=`(echo "${line}" |awk '{print $2}')` lost_crs+=("${line}") fi if [ "${mng}" = '3' ];then mng=`echo ${all_host[${#all_host[@]}-1]}` no_eps+=("${mng}") fi done < $rfile #echo "This is ${all_host[@]}" for item in ${count[@]};do if [ "${item}" = '3' ];then r_chk=`expr "${r_chk}" + 1` fi done non_ep=$(($cnt * 3)) total=0 n=${#count[@]} n=$((n - 1)) while [ "${n}" -ge 0 ]; do total=$((count[$n] + $total)) r_total=$(($total - $non_ep)) n=$((n - 1)) done echo "Total Count = $r_total" total_cr=`expr "${cnt}" + "${cnt1}"` con_rate=`echo "scale=2; 1-($cnt1/$cnt)" | bc` con_rate2=`echo "scale=2; $con_rate*100" | bc` echo "Connection Rate = $con_rate2 %" echo "Number of Connected = $cnt" echo -e "\n" echo -e "Number without Ps = $r_chk" echo -e " -without Ps-\n ${no_es[@]}" echo -e "\n" echo "Number of Lost = $cnt1" #echo -e "\n" if [ "${cnt1}" -gt 0 ];then echo -e " -Lost Connection-\n ${lost_rs[@]}" else echo " -All Connected-" fi

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/12/19 02:31
2017/12/19 15:33