Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Backticks - break command into multiple lines?

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.

like image 422
asfallows Avatar asked Apr 03 '12 17:04

asfallows


4 Answers

You can escape carriage returns with a \:

`ls -l \
 | grep drw-`
like image 187
Mark Thomas Avatar answered Sep 19 '22 19:09

Mark Thomas


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.

like image 32
Andrew Marshall Avatar answered Sep 19 '22 19:09

Andrew Marshall


Use %x:

%x( ls -l |
    grep drw- )

Another:

%x(
  echo a
  echo b
  echo c
)
# => "a\nb\nc\n"
like image 37
konsolebox Avatar answered Sep 19 '22 19:09

konsolebox


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}`
like image 38
jefflunt Avatar answered Sep 17 '22 19:09

jefflunt