1

I'm trying to list an array of directory names using a while loop in a bash script.

The loop code is the following (where $len is the length of $folderArray):

i=0
while [ $i -lt $len ]; do
  echo "$i: ${folderArray[$i]}"
  let i++
done

However, my output is displayed as follows:

0: folder1
folder2
folder3
etc.

Why is the "1:" and "2:" not displayed for folder2 and folder3?

I read about using process substitution to solve this but I'm not sure how that would help here.

2 Answers 2

3

It shows that you stored all items in one element of an array:

"${folderArray[0]}"

If you tried to do some word splitting before that, you probably weren't able to split them at all. Consider checking that code that you use to store lines to folderArray.

Sign up to request clarification or add additional context in comments.

3 Comments

Or possibly that the other items start with \r, but your explanation is more likely.
I set it equal to: ssh -l $remoteUser $remoteHost \"ls $remoteDir\"
Use find and readarray instead: readarray -t folderArray < <(exec ssh -l "$remoteUser" "$remoteHost" "find \"$remoteDir\" -maxdepth 1 -mindepth 1 -printf '%f\n'")
1

First check what is actually stored in the first element of your folderArray array. Most likely this is in ${folderArray[0]}:

folder1
folder2
folder3

and your while loop passes through this in one iteration.

Test this by just saying echo "${folderArray[0]}"

In other words: No variable is disappearing. Your loop just has one iteration.


Edit: Based on your comment, maybe something like this:

folderArray=$(ssh ${remoteUser}@${remoteHost} "ls $remoteDir")
count=0
for f in $folderArray ; do
  echo "$count: $f"
  ((count++))
done

1 Comment

You're right! I tried to put the array of folder names into folderArray using this code: folderArray="ssh -l $remoteUser $remoteHost \"ls $remoteDir\""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.