2

I am trying to run a shell fragment with the bash interpreter. Using the -c flag allows me to provide the commands directly into command line without writing to a file. This is required for my usage.

Example working:

$ bash -c 'free -m'

The problem is the actual shell fragment I want to run has single quotes in it.

find / -type f -size +50M -exec ls -lh {} \; | awk '{ print $9 ": " $5 }' 

I figured simply escaping the quotes would work:

$ bash -c 'find / -type f -size +50M -exec ls -lh {} \; | awk \'{ print $9 ": " $5 }\''

But this does not work. It does not execute the command.

Additionally, same sort of problem, I need to be able to execute Node.js from the command line without writing to a file.

$ node -e 'console.log("hello");'

The above works, but:

$ node -e 'console.log('hello');'

and

$ node -e 'console.log(\'hello\');'

Both break.

Ideas? Thanks.

Justin
  • 5,008
  • 19
  • 58
  • 82

1 Answers1

4

Try this:

$ bash -c $'find / -type f -size +50M -exec ls -lh {} \; | awk \'{ print $9 ": " $5 }\''

From the man bash:

   Words of the form $'string' are treated specially.  The word expands to string,  with  backslash-escaped
   characters  replaced  as  specified by the ANSI C standard.  Backslash escape sequences, if present, are
   decoded as follows:
          \a     alert (bell)
          \b     backspace
          \e     an escape character
          \f     form feed
          \n     new line
          \r     carriage return
          \t     horizontal tab
          \v     vertical tab
          \\     backslash
          \'     single quote
          \nnn   the eight-bit character whose value is the octal value nnn (one to three digits)
          \xHH   the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)
          \cx    a control-x character
quanta
  • 50,327
  • 19
  • 152
  • 213
  • Crazy, what does the `$` do? Seems to work in both `bash -c` and `node -e`. I assume this trick will work for `perl -e` and `python -c` as well. – Justin Aug 02 '12 at 05:03
  • I shouldn't have to worry about escaping anything but single quotes inside the command right? – Justin Aug 02 '12 at 05:05
  • 1
    FYI, the `bash` `$` quote trick is also quite useful if you want to [send a carriage-return through the bash CLI](http://stackoverflow.com/a/11226397/667301) – Mike Pennington Aug 02 '12 at 05:06