0

When doing server maintenance, I often find myself writing multi-level nested commands, so as:

for server in A B C; do sh -c "ssh $server 'mysql db -e \"select where line like \\\"%abc%\\\"\"'&"; done

This may be a contrived example, but it's really the kind of thing I have to do sometimes for some odd, ad-hoc task.

The problem is the quotes. As you go to deeper levels, you have to start escaping the quotes, escaping dollar signs, and escaping the escaping. Using single quotes helps avoid one level, but that's it.

I began working on a solution for myself, inspired by the qq() function in perl, but I thought I'd ask around first: is there a tool, method or framework that will make it easier to write these nested commands without getting bogged down with backslashes?

5
  • Why did you wrap the whole thing in sh -c "" that just adds yet another layer of quoting.
    – geirha
    Jan 2, 2014 at 8:04
  • @geirha Note the & at the end there. This makes all the ssh commands run in parallel.
    – itsadok
    Jan 2, 2014 at 8:57
  • @geirha Oh, sorry, I see your point now.
    – itsadok
    Jan 2, 2014 at 8:59
  • @geirha If I don't use sh -c, I get a bunch of job notifications in the console.
    – itsadok
    Jan 2, 2014 at 10:17
  • only if you run it from an interactive shell. If you put it in a file and run it as a script, you should not get job control notifications, since job control is only enabled for interactive shells.
    – geirha
    Jan 2, 2014 at 14:30

2 Answers 2

1

You can avoid most layers of quoting by passing the mysql commands via stdin instead of via argv:

for server in A B C; do
    ssh "$server" 'mysql db' <<< "select * from foo where line like '%abc%';" &
done
wait

For a more generic answer, see http://mywiki.wooledge.org/BashFAQ/096

0

Try this:

echo "ssh $server 'mysql db....'" | sh

It decreases the nesting level, and also makes it much easier for you because you can just run the echo command until you get the exact command you want run after all escaping.

1
  • This looks like it has the exact same level of nesting.
    – itsadok
    Jan 2, 2014 at 7:57

You must log in to answer this question.

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