2017-08-31 119 views
0

我一直在編碼bash腳本通過讀取命令,以接受一系列的大寫字母,一次一個的輸入。輸入以0結尾。在所有有效輸入字母和有效輸入字母總數中查找並顯示按字母順序排列的第一個字母。如何找到從輸入字母表中的第一個字母和計數輸入字母

如果我,例如,d,G,T,W,Q,3,B,1,d,S,0的輸入,預期的輸出是:

「3是一個無效的輸入」

‘1是一個無效的輸入’ ‘在所有輸入拼音的第一個字母是B’

‘你輸入8個有效的字母。’

下面是我的一些代碼,並請讓我知道我得解決

#!/bin/bash 
IV=() 
loop=-1 
c=Z 
ac=0 

while [ $loop -gt 0] || [ $loop -t 0] 
do 
echo "Enter an uppercase Alphabet" 
read b 
if [[ $b = [A-Z] ]] 
then 
     ac=`expr $ac +1` 
     if [ $b \< $c ] 
     then 
       c=$b 
     fi 

elif [ $b = "0" ] 
then 
     loop=`expr $loop +1` 
     for i in "${IV[@]}" 
     do 
     echo $i "is an invalid input" 
     done 
     echo "The first letter in Alphabetical order of all input is" $c 
     echo "You have entered" $ac "valid letters." 

else 
     IV[@]=$b 
fi 
done 

所以,我的問題是,如果我輸入無效的字符串或整型,輸出類似 「IV [@]:壞數組下標」

+0

什麼是你正面臨着與發佈代碼的問題?什麼不適合你?您是否在尋找評論?那麼也許更擅長https://codereview.stackexchange.com/ 適合了作爲一個開始,家當更改爲'#!/斌/慶典-x'並期待在輸出... –

+0

爲該啊對不起。我的問題是,如果我輸入無效的字符串或整型,輸出是像「IV [@]:壞數組下標」 –

+1

那是因爲你不能做'IV [@] = $ B'。 '@'說明符允許您列出所有元素,但不能像您所擁有的那樣將它用作賦值的「左值」。爲什麼'ac ='expr $ ac + 1'?一個簡單的((aC++))就是需要的。 'expr'可以工作,但* * * *。什麼是'[$ b \ <$ c]'?你有沒有通過[** ShellCheck.net **](http://www.shellcheck.net/)運行你的代碼? –

回答

0

它看起來像你的代碼是接近做你希望它能做到。有了一些調整,和便利參數擴展把所有的輸入爲大寫,你可以做這樣的事情:

#!/bin/bash 

declare -a IV # invalid values 
c=Z 
ac=0 

while : 
do 
    echo "Enter an uppercase Alphabet" 
    read b 
    b="${b^^}" 
    if [[ $b = [A-Z] ]] 
    then 
     ((ac++)) 
     [ "$b" \< "$c" ] && c="$b" 
    elif [ "$b" -eq "0" ] 
    then 
     for i in "${IV[@]}" 
     do 
      echo $i "is an invalid input" 
      done 
      echo "The first letter in Alphabetical order of all input is" $c 
      echo "You have entered" $ac "valid letters." 
     break; 
    else 
     IV+=("$b") 
    fi 
done 

注:我完全刪除了loop值,並用替換它簡單的break看起來像條件​​的更清晰的實現。

示例使用/輸出

$ bash letterseries.sh 
Enter an uppercase Alphabet 
d 
Enter an uppercase Alphabet 
g 
Enter an uppercase Alphabet 
t 
Enter an uppercase Alphabet 
w 
Enter an uppercase Alphabet 
q 
Enter an uppercase Alphabet 
3 
Enter an uppercase Alphabet 
b 
Enter an uppercase Alphabet 
1 
Enter an uppercase Alphabet 
d 
Enter an uppercase Alphabet 
s 
Enter an uppercase Alphabet 
0 
3 is an invalid input 
1 is an invalid input 
The first letter in Alphabetical order of all input is B 
You have entered 8 valid letters. 

這就提供了您的預期產出,以及主變(比曲風其他與((..))b="${b^^}"更改爲大寫,代碼主要是你所得到的。首要的問題是你

IV[@]=$b 

這是無效的語法看起來你打算:

IV+=("$b") 

"$b"的每個值存儲在索引數組IV中。

看東西了,讓我知道,如果我解決你的問題。如果沒有,只需發表評論,我會進一步幫助。

相關問題