Search code examples
bashsshpsqlscp

Pass value of variable to complex command


I am trying to pass value from string variable to complex bash command and I have problem with it. When I executing commands:

files=($(ls abc*))

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 ~/$file'
    ssh user@domain.com 'rm ~/$file'
done

I get some errors. Only 'scp' is right executed but lines after them go fail. I am seeing "missing parameter for psql -f" and "file not found / cannot remove dictionary" What is problem with this code? How to pass string value to ssh commands?


Solution

  • Single quotes will prevent the remote shell from receiving your variable. Don't use ls in scripts. Quote your variables. Use http://shellcheck.net/ before asking for human review.

    for file in abc*
    do
        scp "$file" user@domain.com:~
        ssh user@domain.com "PGPASSWORD='abcd' psql -h domain.com -U user -d dbb -f ~/'$file'; 
            rm ~/'$file'"
    done
    

    The quoting here is slightly tricky, and won't work if your file names might contain e.g. literal single quotes. The double quotes cause the local shell to expand $file; then the expanded value is in single quotes to prevent the remote ssh from manipulating it any further.

    I took out the array because it didn't seem to serve any useful purpose. If you want an array, assign it simply with a wildcard:

    files=(abc*)