Viren
Viren

Reputation: 5962

What's wrong with my shell script

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

Upvotes: 1

Views: 152

Answers (1)

Dennis Williamson
Dennis Williamson

Reputation: 360625

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

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

echo "${#ARR[@]}"

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

Use globs instead of ls.

Use arrays instead of strings.

Quote variables when they are expanded.

Upvotes: 4

Related Questions