5

I found this solution that works for me, but I don't understand how it does work given that the sed command encloses its own parameter in single quotes, and the whole ssh command is also passed in single quotes. This is being run from OSX (bsd).

ssh -t -p 22 root@thehost 'for user in $(/bin/ls -A1 /var/cpanel/users) ; do if grep -q RS=paper /var/cpanel/users/${user}; then sed -i 's/^RS=paper_lantern$/RS=x3/' /var/cpanel/users/${user}; fi; done'

Can someone explain to me why this works, and why I didn't need to escape the single quotes for the sed command - I can't find a reference anywhere? Thanks.

1 Answer 1

6

You don't because your sed string doesn't have to be quoted, and in fact, on the remote server, it's not quoted.

What's passed as argument to your ssh command looks like this:

for user in $(/bin/ls -A1 /var/cpanel/users) ; do if grep -q RS=paper /var/cpanel/users/${user}; then sed -i s/^RS=paper_lantern$/RS=x3/ /var/cpanel/users/${user}; fi; done

And it works fine because there are no spaces inside the argument of your sed command.

If you want to pass a sed argument with spaces, you should escape your single quotes like so:

'for user in $(/bin/ls -A1 /var/cpanel/users) ; do if grep -q RS=paper /var/cpanel/users/${user}; then sed -i '\''s/^RS=paper_lantern$/RS=x3/'\'' /var/cpanel/users/${user}; fi; done'

With single quotes, you can't escape single quotes like this: \'

You have to use a trick. You have to close quotes, escape your ' and re-open quotes. ('\'')

1
  • Thank you - it seems so obvious now! I'm sure my question is a duplicate - so I'm sorry for taking your time!
    – Santrix
    Apr 18, 2015 at 7:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .