1

I have a bash script wrapped in " " so I need to use ' ' for my grep command but it doesn't work. I can't switch the quotes because then the variables are not expanded.

#!/bin/bash

PWD=`pwd`
source "$PWD/AWS.config.sh"

SCRIPT="
cd ~/$APP_PATH;
netstat -ln | grep ':80 ' &> /dev/null;
if [ $? -eq 0 ]; then
    echo something on 80;
else
    echo nothing on 80;
fi
"
ssh -i $EC2_PEM_FILE $APP_HOST $SCRIPT

So

netstat -ln | grep ':anyporthere ' &> /dev/null;

always seems to return $? as 0 suggesting a match when there clearly is none.

As I mentioned if I switch to " " and ' ' for the enclosing script, it works but then the script variables are not expanded which is a problem.

Please help.

  • Have you tried escaping the inner quotes? grep \":80 \" &> /dev/null – MattDMo Mar 19 '14 at 21:10
2

The $? variable in the script is being substituted when you assign the variable, not on the remote host

#!/bin/bash
source "$PWD/AWS.config.sh"

ssh -i "$EC2_PEM_FILE" "$APP_HOST" << END_SCRIPT
    cd ~/"$APP_PATH"
    netstat -ln | grep -q ':80 '
    if [ \$? -eq 0 ]; then
        echo something on 80
    else
        echo nothing on 80
    fi
END_SCRIPT
  • There's already a bash variable named PWD, so you don't need to assign to it.
  • Get into the habit of quoting your variables, unless you know when to not do it.
  • grep -q is quiet but returns the same exit status. More efficient too, because it exits immediately if a match is found, not searching the rest of the file.
  • do you need to cd just to run netstat?

You could also use the short-circuit boolean operators:

ssh -i "$EC2_PEM_FILE" "$APP_HOST" "netstat -ln | grep -q ':80 ' && echo something on 80 || echo nothing on 80"
END_SCRIPT
  • no, the cd was just to illustrate the use of variable inside the script. – Alasdair P Mar 20 '14 at 17:03
0

Solved by concatenating strings with differing quotes.. quite hacky though. Still prefer a nicer solution

SCRIPT="
blah;
blah;
"
SCRIPT+='
this grep bit " "
'

SCRIPT+="
the rest
"

Fugly..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.