slimlambda
slimlambda

Reputation: 153

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?

Upvotes: 0

Views: 240

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295325

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

Upvotes: 8

Raindy Long
Raindy Long

Reputation: 61

[command server] ------> [remote server]

The better way is to create shell script in the "remote server" , and run the command in the "command server" such as :

ssh ${remoteserver} "/bin/bash /foo/foo.sh"

It will solve many problem , the aim is to make things simple but not complex .

Upvotes: 1

Related Questions