Pass list of arguments to a command for each line

In a bash script: I have this list of arguments (or directories in this case):

Directories=(
/Dir1/
/Dir2/
/Dir3/
)
And I want every item (or line) of this list, to be passed as a argument to a command. Like this:

cd /Dir1/
cd /Dir2/
cd /Dir3/
(Replace "cd" with any command)

I tried this:
cd ${Directories[@]}
But that results in this:
cd /Dir1/ /Dir2/ /Dir3/

How I can make the script run the command each time with a new line, until it reaches the end?

Upvotes: 1

Views: 105

Answers (2)

mklement0
mklement0

Reputation: 437111

Update: In fact, the solution below is not suitable for commands meant to alter the current shell's environment, such as cd. It is suitable for commands that invoke external utilities. For commands designed to alter the current shell's environment, see Balaji Sukumaran's answer.

xargs is the right tool for the job:

printf '%s\n' "${Directories[@]}" | xargs -I % <externalUtility> %
  • printf '%s\n' "${Directories[@]}" prints each array element on its own line.
  • xargs -I % <externalUtility> % invokes external command <externalUtility> for each input line, passing the line as a single argument; % is a freely chosen placeholder.

Upvotes: 1

Balaji Sukumaran
Balaji Sukumaran

Reputation: 185

For loop can be used as well

#!/bin/bash
Directories=( /dir1 /dir2 /dir3)
for dir in "${Directories[@]}"
do
  cd "${dir}"
done

Upvotes: 5

Related Questions