Linux – Executing bash code interactively using -c flag

bashescapinglinux

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.

Best Answer

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