Ruby system calls

The programming language Ruby allows to make system calls redirected to the shell. This is useful to call certain local applications or read system information. It even allows to script certain tasks via Ruby.

Different methods

There are 3 different syntax of system calls within the Ruby programming language:

system call

# irb> system('ls -l')


# irb> `ls -l`


# irb> %x[ls -l]

Getting output

Using the backticks (`command`) and the %x[command] methods allow to get the output of the system call returned as a string. Therefore it is possible to store this kind of information within a variable.

Example 1:

# irb> commandOutput = `ls -l`

Example 2:

# irb> commandOutput = %x[ls -l]

commandOutput contains the output of the command ls -l as a string.

Using Ruby variables

The backticks (`command`) and the %x[command] methods allows to include Ruby variables within the `command` string with the following escape characters:


Example 1:

# irb> filename = example.txt
# irb> `ls -l | grep #{filename}`

Example 2:

# irb> filename = example.txt
# irb> %x[ls -l | grep #{filename}]

See Also

External links