Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is or was there ever a version of Unix where the shell builtin "if" was a command (like /bin/[ and /bin/test)?

share|improve this question
up vote 2 down vote accepted

Highly unlikely. if is not a command; it is part of the sh shell syntax, with different parsing rules in order to allow command lists, nested if's, and so on.

For example, the following would be plain impossible if if were a command, since the parser would just stop at if test -e file; without considering the rest.

if test -e file; then
    echo "File exists"
    if touch file; then
        echo "File created"
        echo "File couldn't be created"

Or this:

if case $path in
   ~/trash/*)  false;;
   ~/*)        true;;
   /proc/*)    false;;
   *)          true;;
esac; then
   backup "$path"
   echo "skipping $path"

Unless you wanted to resort to such things as quoting... lots of quoting. And it would require either reimplementing the same shell parser inside if. If you simply had it spawn a new imaginarysh -c <argument>, then it would be impossible to modify variables inside the command lists.

/bin/if "test -e file" "echo \"File exists\"" "if \"touch file\" \"echo File created\" \"echo \\\"File couldn\\\'t be created\\\"\""

(Aside: if is actually a command in the Tcl programming language, and it works just like the example above, except with balanced { } for quoting blocks of code.)

But on the second thought, if if were a command, it would become impossible to modify variables inside the command lists anyway. Anything modified inside the if arguments would be impossible to reach the main process.

Finally, there is absolutely no advantage to implementing if externally. In shells, testing the condition consists of 1) running the command, and 2) checking its exit code. If if were external, your shell would have to do the same anyway, otherwise it wouldn't know if if succeeded or failed. (The same functionality is used in || and && conditionals, too.)

(Aside: In early Unix prototypes, chdir was an external command.)

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .