Search code examples
rubyshellbackticks

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.


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.