What is problem with this code? How to pass string value to ssh commands?
One of the important distinctions between quoting with double quotes ("
) and quoting with single quotes ('
) is that the latter suppresses parameter expansion. You need to either move the $file
outside the quotes, or change to double-quote style. Additionally, however, you should properly quote the expansions of $file
, else you leave yourself open to breakage or even nasty surprises in the event of unusual file names, such as those containing spaces.
Moreover, the fact that you are formatting a command string that will be processed by a different shell adds some complication. The easiest way to be sure that you get the quoting right is to use bash's printf
builtin, whose %q
formatting option serves exactly the purpose of quoting an arbitrary string so that the result can be re-read as shell input to reproduce the same string. Overall, then, here's my recommendation for the loop:
for file in "${files[@]}"
do
scp "${file}" user@domain.com:~
ssh user@domain.com "PGPASSWORD='abcd' psql -h domain.com -U user -d dbb -f $(printf %q "~/${file}")"
ssh user@domain.com "rm $(printf %q "~/${file}")"
done