Skip to content
Advertisement

Bash script runs one command before previous. I want them one after the other

So part of my script is as follows:

ssh user@$remoteServer "
    cd ~/a/b/c/;
    echo -e 'blah blah'
    sleep 1 # Added this just to make sure it waits.
    foo=`grep something xyz.log |sed 's/something//g' |sed 's/something-else//g'`
    echo $foo > ~/xyz.list
    exit "

In my output I see:

grep: xyz.log: No such file or directory
blah blah

Whereas when I ssh to the server, xyz.log does exist within ~/a/b/c/

Why is the grep statement getting executed before the echo statement?

Can someone please help?

Advertisement

Answer

The problem here is that your command in backticks is being run locally, not on the remote end of the SSH connection. Thus, it runs before you’ve even connected to the remote system at all! (This is true for all expansions that run in double-quotes, so the $foo in echo $foo as well).

Use a quoted heredoc to protect your code against local evaluation:

ssh user@$remoteServer bash -s <<'EOF'
    cd ~/a/b/c/;
    echo -e 'blah blah'
    sleep 1 # Added this just to make sure it waits.
    foo=`grep something xyz.log |sed 's/something//g' |sed 's/something-else//g'`
    echo $foo > ~/xyz.list
    exit
EOF

If you want to pass through a variable from the local side, the easy way is with positional parameters:

printf -v varsStr '%q ' "$varOne" "$varTwo"
ssh "user@$remoteServer" "bash -s $varsStr" <<'EOF'
  varOne=$1; varTwo=$2 # set as remote variables
  echo "Remote value of varOne is $varOne"
  echo "Remote value of varTwo is $varTwo"
EOF
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement