Thursday 16 February 2017

Executing ubuntu shell commands in ruby programming


1. system
   
    The system method calls a system program. We have to provide the command as a string argument to this method.
    This will always return value is either true, false or nil.

    Example -
       
        system("df -h")
   
    Above command gives disk information but it will return true.

       Filesystem      Size  Used Avail Use% Mounted on
        udev            1.9G     0  1.9G   0% /dev
        tmpfs           386M  6.4M  380M   2% /run
        /dev/sda1       141G   74G   61G  56% /
        tmpfs           1.9G  523M  1.4G  28% /dev/shm
        tmpfs           5.0M  4.0K  5.0M   1% /run/lock
        tmpfs           1.9G     0  1.9G   0% /sys/fs/cgroup
        /dev/sda5       314G   67M  298G   1% /drive
        cgmfs           100K     0  100K   0% /run/cgmanager/fs
        tmpfs           386M   76K  386M   1% /run/user/1000
         => true

    system eats up all the exceptions. So the main operation never needs to worry about capturing an exception raised from the child process.

2. exec

    By using Kernel#exec replaces the current process by running the external command. The method can take a string as argument. When using     more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

    Example -

        exec 'date'

    Above command returns system date like this

         =>    Fri Feb 17 10:27:16 IST 2017

3. Backticks

    Backtick returns the standard output of the operation. As opposed to the above approach, the command is not provided through a string,         but by putting it inside a backticks pair.

    Example -

        `date`

    Above command returns system date like this

         =>    "Fri Feb 17 10:32:35 IST 2017\n"

    Backtick operation forks the master process and the operation is executed in a new process. If there is an exception in the sub-process then that exception is given to the main process and the main process might terminate if exception is not handled.

4. %x()

    Using %x is an alternative to the back-ticks style. It allows you to have different delimiter.

    Example -

        %x('date')

     Above command returns system date like this

         => "Fri Feb 17 10:37:14 IST 2017\n"

5. Open3.popen3

    Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here         Open3.popen3 comes is very usefull

    Example -

        require 'open3'
        cmd = 'git push origin master'
        Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
          puts "stdout is:" + stdout.read
          puts "stderr is:" + stderr.read
        end

6. $?

    You can check process status by running $?.

1 comment: