Friday, April 23, 2010

LINUX: If-Else Shell Command (OR operator)

A useful command is the || operator that can be used on the linux command line. It is similar to saying "if not, then do". An example of usage would be if you wanted to put something in a script that would launch a tool, say cervisia for example, but you want to make sure that if it is already running, another instance isn't launched, you could do the following.
ps ux | grep -q cervisi[a] || cervisia . &

Now, there is an interesting thing being done with grep. In order to prevent grep from finding itself in the running processes list, use a regular expression for the last character of the process name you are looking for. Hence, the "a" in cervisia is put in brackets [] to make it a regular expression and prevent the duplication of showing the grep command in the results. Note that the two commands above, ps and grep, can be accomplished with the more efficient pgrep command, which is the combination of the two commands already part of the linux shell.

No comments:

Post a Comment