25

In Ruby, I know I can execute a shell command with backticks like so:

`ls -l | grep drw-`

However, I'm working on a script which calls for a few fairly long shell commands, and for readability's sake I'd like to be able to break it out onto multiple lines. I'm assuming I can't just throw in a plus sign as with Strings, but I'm curious if there is either a command concatenation technique of some other way to cleanly break a long command string into multiple lines of source code.

1
  • 1
    Personally, if I need to call some long shell commands, I'd put them into a shell script, and then call that and capture its output. I'd rather maintain shell scripts separately from my Ruby code. Commented Apr 3, 2012 at 18:50

4 Answers 4

56

You can escape carriage returns with a \:

`ls -l \
 | grep drw-`
0
17

You can use interpolation:

`#{"ls -l" +
   "| grep drw-"}`

or put the command into a variable and interpolate the variable:

cmd = "ls -l" +
      "| grep drw-"
`#{cmd}`

Depending on your needs, you may also be able to use a different method of running the shell command, such as system, but note its behavior is not exactly the same as backticks.

1
  • Thanks, I figured it would be something simple but I had trouble forming my google query to get something meaningful back.
    – asfallows
    Commented Apr 3, 2012 at 17:58
13

Use %x:

%x( ls -l |
    grep drw- )

Another:

%x(
  echo a
  echo b
  echo c
)
# => "a\nb\nc\n"
1
  • 2
    Note that it's crucial to have pipes (|) at the end of the first line, not at the beginning of the second.
    – codener
    Commented Aug 11, 2016 at 13:39
1

You can also do this with explicit \n:

cmd_str = "ls -l\n" +
          "| grep drw-"

...and then put the combined string inside backticks.

`#{cmd_str}`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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