0

I have a bash script in which i define a certain path as such:

MY_PATH=/to/my/path

I also have a set of directories within MY_PATH and I store these directories in an array, as such:

DIRECTORIES="/dir1/
/dir2/
/dir3/"

What I want to do is iterate over all the $DIRECTORIES in $MY_PATH, so I tried this:

for dir in $MY_PATH$DIRECTORIES
do
    echo "Processing $dir"
end

However, this gives the following undesired output:

Processing /to/my/path/dir1/           #Correct!
Processing /dir2/                      #What I want: Processing /to/my/path/dir2/
Processing /dir3/                      #What I want: Processing /to/my/path/dir3/

Is there any way to prevent iteration over $MY_PATH while preserving iteration over $DIRECTORIES so that I can achieve the desired output (see above)?

3 Answers 3

3
for dir in $DIRECTORIES; do
  path="$MY_PATH/$dir"
  echo "Processing $path"
done
Sign up to request clarification or add additional context in comments.

Comments

2

That's not an array, btw. Using an array would look like this:

MY_PATH=/to/my/path
DIRECTORIES=(dir1 dir2 dir3)
for dir in "${DIRECTORIES[@]}"; do
  path="$MY_PATH/$dir"
  echo "Processing $path"
done

(and this is not an answer, but the above code wouldn't fit in a comment.:))

Comments

0

In case there are spaces in folder names

MY_PATH="/to/my/path"

And you are using newlines to separate folders as before

DIRECTORIES="/dir1/
/dir2/
/dir3/"

A slightly safer loop would be

OLDIFS=$IFS
IFS=$'\n'
for dir in $DIRECTORIES; do
  path="$MY_PATH/$dir"
  echo "Processing $path"
done
IFS=$OLDIFS

Comments

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.