No such file or directory in Heredoc, Bash

1.1k views Asked by At

I am deeply confused by Bash's Heredoc construct behaviour.

Here is what I am doing:

#!/bin/bash
user="some_user"
server="some_server"
address="$user"@"$server"

printf -v user_q '%q' "$user"

function run {
    ssh "$address" /bin/bash "$@"
}

run << SSHCONNECTION1
    sudo dpkg-query -W -f='${Status}' nano 2>/dev/null | grep -c "ok installed" > /home/$user_q/check.txt

    softwareInstalled=$(cat /home/$user_q/check.txt)

SSHCONNECTION1

What I get is

cat: /home/some_user/check.txt: No such file or directory

This is very bizarre, because the file exists if I was to connect using SSH and check the following path.

What am I doing wrong? File is not executable, just a text file. Thank you.

1

There are 1 answers

3
Charles Duffy On BEST ANSWER

If you want the cat to run remotely, rather than locally during the heredoc's evaluation, escape the $ in the $(...):

softwareInstalled=\$(cat /home/$user_q/check.txt)

Of course, this only has meaning if some other part of your remote script then refers to "$softwareInstalled" (or, since it's in an unquoted heredoc, "\$softwareInstalled").