24

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.

asfallows
  • 5,998
  • 6
  • 29
  • 48
  • 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. – the Tin Man Apr 03 '12 at 18:50

4 Answers4

54

You can escape carriage returns with a \:

`ls -l \
 | grep drw-`
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
16

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.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • Thanks, I figured it would be something simple but I had trouble forming my google query to get something meaningful back. – asfallows Apr 03 '12 at 17:58
13

Use %x:

%x( ls -l |
    grep drw- )

Another:

%x(
  echo a
  echo b
  echo c
)
# => "a\nb\nc\n"
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • 2
    Note that it's crucial to have pipes (`|`) at the end of the first line, not at the beginning of the second. – codener Aug 11 '16 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}`
jefflunt
  • 33,527
  • 7
  • 88
  • 126