Showing results for 
Search instead for 
Did you mean: 

exec command

Occasional Visitor

exec command

hi i just wanna know what does the exec command do?
i read up man pages etc..but i still dont understand..can anyone explain more clearly?

also..what is the difference between: exec ls -l
and ls -l

and could pls explain to me in detail what these commands do:
1) exec 3 sort <&3
exec 3<&-

2) exec 4>newfile
ls >&4
exec 5<&4

thanks in advance!
James Roper

Re: exec command

The exec command executes a command and replaces the current shell command with that command. The man page you read is likely to be from section 3 of the manual. That page describes the exec system call in C programming... This is not what you're looking for.

When you type ls in your shell, the shell will spawn a new process, and then run exec ls in that new process. This process will terminate as soon as ls finishes. After ls has completed, the shell will resume normal execution. Running exec ls however will not spawn a new process. Rather, ls will replace the shell in the current process. As soon as ls has finished, the process will finish, and will not go back to the shell, as it finished when you ran exec ls.

This is what happens when you give exec a command to run. If you give it no command however, it will simply apply all redirections that you give it to the current process.

So, with the above sequence of commands (I hope you understand file descriptors and input output redirection otherwise this may go straight over your head:

exec 3opens file descriptor 3 with the input from datfile connected to it.
sort <&3
runs the sort command but first redirects its standard input to file descriptor 3, which of course has already been pointed to datfile.
exec 3<&-
closes file descriptor 3.

This sequence does exactly the same thing as sort < datfile, the output being the lines of datfile sorted in alphabetical order on the standard output.

As these commands do a simple thing in a hard way, my guess is that you're asking this for a school assignment. I've explained the first one, I'm not going to do all the work for you. Read man bash, this explains both exec and redirection, if you can find them, the man file is HUGE.

I'm only a 3rd year software engineering student, you should be able to do it :)

If my whole world were fake, then none of it would be fake, because reality is what is real to me
Occasional Visitor

Re: exec command

thanks James for your help. Your explanation cleared things up for me!
thanks again!
Balaji N
Honored Contributor

Re: exec command

so, how abt assigning points.
Its Always Important To Know, What People Think Of You. Then, Of Course, You Surprise Them By Giving More.