exec < filename - what does this do?
Solution 1
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.
Solution 2
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.
Related videos on Youtube
NWS
Updated on September 18, 2022Comments
-
NWS almost 2 years
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.
-
NWS almost 12 yearsso as there is actually no need to modify the file or its descriptors, its essentially a null operation ?
-
jlliagre almost 12 yearsIt 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.
-
jw013 almost 12 years@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. -
jmend about 10 yearsThis is actually a very useful hack, I had no idea you could change stdin of the running shell.