call bash script with array of strings with spaces as argument

I am fairly new to bash. I want to call a script located on a remote linux machine, passing some normal arguments and one array. The array contains string elements which may have spaces.

I wrote a minimal example:

on the server side: copyFiles.sh

#!/bin/bash
msg=$1
msg2=$2
shift
shift
arr=("$@") # Rebuild the array with rest of arguments
for ((i = 0; i < ${#arr[@]}; i++))
do echo $msg $msg2 "${arr[$i]}"
done

On the host side:

first="first"
second="second"
array=("arra y1" "array2" "array3")
plink -ssh username@hostname -pw mypwd -batch " bash scripts/copyFiles.sh $first $second "${array[@]}" "

Output:

first second arra
first second y1
first second array2
first second array3

What I want:

first second arra y1
first second array2
first second array3

Thanks

1

1 Answer

I think you just need to use \" for space separated arguments. Did you try to escape string with spaces in the following way:

"\"arra y1\""

I think it may solve your issue.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like