1

I have a shell script which has a for loop that prints the value of an array element. The array size is 2 but when running the for loop with that array I'm not getting proper output.

Here is the shell script:

#!/bin/bash

arry=$(ls /home/developer/.ssh/  | grep "\.pub")
declare -a ARR
i=0
for key in $arry
do
  ARR[i]=$(echo $key | sed 's/.pub//g')
  i=$((i+1))
done
echo ${#ARR[@]}
## the below for loop is not iterating as expected
for pri in $ARR
do
 echo $pri
done

Now instead of giving the output

2
a
heroku

The above code produces:

2
a

What is wrong with the above shell code?

I'm relatively new to shell script so pardon my code I you feel it not good

Attaching screenshot of the output enter image description here

4

1 に答える 1

4
#!/bin/bash
arry=(/home/developer/.ssh/*.pub)

ARR=(${arry[@]%%.pub})    # strip the extensions

echo "${#ARR[@]}"

for pri in "${ARR[@]}"
do
    echo "$pri"
done

の代わりにグロブを使用しlsます。

文字列の代わりに配列を使用してください。

展開されたときに変数を引用します。

于 2012-05-27T14:49:57.670 に答える