Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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
share|improve this answer
    
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 2 '12 at 5:03
    
I shouldn't have to worry about escaping anything but single quotes inside the command right? –  Justin Aug 2 '12 at 5:05
1  
FYI, the bash $ quote trick is also quite useful if you want to send a carriage-return through the bash CLI –  Mike Pennington Aug 2 '12 at 5:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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