Question

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.

Était-ce utile?

La solution

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.

Autres conseils

You can escape carriage returns with a \:

`ls -l \
 | grep drw-`

Use %x:

%x( ls -l |
    grep drw- )

Another:

%x(
  echo a
  echo b
  echo c
)
# => "a\nb\nc\n"

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}`
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top