3

I have found the following code snippet (sh):

    TESTFILE=$TEST_PATH/test.out
    if [ -f $TESTFILE ]
    then
        exec < $TESTFILE
    else
        echo "$TEST_PATH: no test.out file"
    fi

the focus of my question is, what is this line doing? (the rest i understand!)

        exec < $TESTFILE

The file is not executable, nor is another process invoked, and i am having no luck finding what exec does on a plain text file.

7

From the POSIX description of exec:

exec - execute commands and open, close, or copy file descriptors

In this case, there is no command, so only file descriptors are modified. Normally, redirections you write on the command line affect the command on that line. exec is how you do redirections on the currently executing shell.

  • so as there is actually no need to modify the file or its descriptors, its essentially a null operation ? – NWS Aug 29 '12 at 15:14
  • 3
    It is not completely a null operation. The remaining of the scripts will pick its standard input from $TESTFILE starting from this instruction instead of whatever was stdin before, presumably the keyboard for interactive scripts. – jlliagre Aug 29 '12 at 15:26
  • @NWS Whether something is a null operation depends on what it does, not whether what it does is actually needed. A null operation does nothing by definition except possibly pass some time. Modifying file descriptors is not nothing, so that is not a null operation. Running exec by itself could be considered a null operation, except for setting $? to 0. – jw013 Aug 29 '12 at 16:52
  • This is actually a very useful hack, I had no idea you could change stdin of the running shell. – pjc50 Jun 16 '14 at 14:19
9

Intuitive understanding may be helped by observing this pattern:

cmd                  # fork; execute cmd in child
cmd < /dev/null      # fork; redirect stdin and execute cmd in child
exec cmd             # execute cmd; no fork
exec cmd < /dev/null # redirect stdin and execute cmd; no fork
exec < /dev/null     # redirect stdin; no fork and no execution

See, exec isn't really a thing. It's an anti-thing. It doesn't mean "execute" at all. It means "don't fork". It makes the command's redirection and/or command execution happen in the current process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.