Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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.

share|improve this answer
    
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
add comment

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.

share|improve this answer
1  
Thanks for this answer, it was a tremendous help. –  sbeskur Sep 4 '12 at 16:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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