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

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

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest