1

Is it possible to call a bash script with an array/list as one of the parameters? I have tried the example below but it fails on the "(". I am trying to get $3 to have a list assigned to it for my script.

bash file_manipulation.sh source_dir target_dir (filename1 filename2)
1
  • No. You can't do this. But $@ is already an array and you can use/copy that and/or manipulate it however you like. What are you trying to do exactly? Commented May 4, 2015 at 20:06

3 Answers 3

5

Do it like this: save the first 2 params and shift them out of positional params, then store the remaining positional params in an array

#!/bin/bash

src=$1
tgt=$2
shift 2
files=( "$@" )

echo "manipulation"
echo " src=$src"
echo " tgt=$tgt"
for ((i=0; i < ${#files[@]}; i++)); do
    echo " file $i: ${files[i]}"
done

So

$ bash file_manipulation.sh source_dir target_dir filename1 filename2
manipulation
 src=source_dir
 tgt=target_dir
 file 0: filename1
 file 1: filename2

You could also just use the positional params like an array:

for file do
    echo file: $file
done
Sign up to request clarification or add additional context in comments.

Comments

2

No, you can only pass strings to a shell script (or whatever other program, in general).

What you can do, however, is to handle some special syntax for arrays you define yourself and parse manually in the shell script. For example, you could use parentheses as delimiters for an array. You would then have to escape them so that they aren't interpreted by the shell:

bash file_manipulation.sh source_dir target_dir \( filename1 filename2 \)

Comments

2
cat file_manipulation.sh 
#!/bin/bash
echo -e "source:\n  $1";
echo -e "target:\n  $2";
echo "files:";
#Convert a String with spaces to array, before delete parenthesis
my_array=(`echo $3 | sed 's/[()]//g'`)
for val in ${my_array[@]}; do
  echo "  $val";
done

#I add quotes to argument
bash file_manipulation.sh source_dir target_dir "(filename1 filename2)"

you get:

source:
  source_dir
target:
  target_dir
files:
  filename1
  filename2

NOTE: it's better without parenthesis

cat file_manipulation.sh 
#!/bin/bash
my_array=( $3 )
for val in ${my_array[@]}; do
  echo "$val";
done

#I add quotes to argument, and without parenthesis
bash file_manipulation.sh source_dir target_dir "filename1 filename2"

NOTE 2: filenames can't contain whitespace.

1 Comment

Either way, you're limited to filenames that don't contain whitespace.

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.