exec

  • english
  • spanish

exec is a built-in shell command that forces a binary to be executed by the currently running shell process instead of forking the process and running the binary on that child process.

When you run a command on a shell-script, it forks a child process and runs the command there. On a syscall level this is the classic:

if( (pid=fork()) == 0) { exec(command); exit(); } wait();

And this is usually what we want, because we will keep running commands after that one. Nevertheless, sometimes this is a problem, like when:

  • we have a program that’s going to monitor a given process, and it doesn’t run properly if there’s an intermediate shell process but we need to run this second process via a shel-script for whatever reasons (to initialize some variables, run the program with nice, whatever)
  • on MacOS we’re running a program via a shell-script and get two icons on the dock, one for the shell and another one for the program

Running a command with exec forces the shell not to fork, but to run the command directly over the shell process. An important thing to note here is that the shell-script will end there, no further commands of the shell script will be executed as the shell process will be substituted by the command process, so to speak.

#!/bin/sh # initialize variables, parse command-line parameters, etc. export IP=$1 exec nice command $*

Shell-script: timestamp

  • english
  • spanish

A one-liner function that, when piped with the output of another command, prepends each line of that command’s output with a timestamp.

Very useful with commands that output a series of lines periodically but without a timestamp (like vmstat), so that you can’t just send their output to a file and go back to it later without a timeframe.

$ function timestamp { while read l; do d=`date +%H:%M:%S`; echo -e "$d $l"; done; }
$ vmstat 1 | timestamp 12:17:03 procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu---- 12:17:03 r b swpd free buff cache si so bi bo in cs us sy id wa 12:17:03 1 0 4 16740 42816 395164 0 0 6 5 174 11 3 1 96 0 12:17:04 0 0 4 16656 42816 395184 0 0 0 0 393 510 1 1 98 0 12:17:05 0 0 4 16656 42816 395184 0 0 0 0 391 781 2 1 98 0 12:17:06 1 0 4 16656 42824 395176 0 0 0 84 462 976 3 1 95 0 12:17:07 0 0 4 16656 42824 395184 0 0 0 0 433 1545 11 3 86 0 12:17:08 0 0 4 16656 42824 395184 0 0 0 0 356 807 1 2 97 0