What happens if you run 'exec ls' in your shell and why? [closed] What happens if you run 'exec ls' in your shell and why? [closed] shell shell

What happens if you run 'exec ls' in your shell and why? [closed]


If you run ls, your shell process will start up another process to run the ls program, then it will wait for it to finish. When it finishes, control is returned to the shell.

With exec ls, you actually replace your shell program in the current process with the ls program so that, when it finishes, there's no shell waiting for it.

Most likely, you will have either a terminal program or init as the parent which is what will take over when your process exits. That's why your shell disappears, because you explicitly told it to.

See this answer for an explanation of the shell/ls (non-exec) situation.


As for your update, the shell does not always create a separate process to do stuff. There are a large number of internal commands (such as cd or alias) that do not involve making other processes (this depends on your shell, of course but, as one example, you can see the bash internal commands by entering man bash-builtins at a command prompt).

exec is one of these. It simply replaces the shell itself (ie, not a forked child process) with the program you specify. That's why it doesn't act as you think.


Exec overrides the current process with another one. Normally when you call "ls" a new process is created that runs as child of your shell. "exec ls" overrides your current shell with the "ls" process. Thus as soon as "ls" terminates your terminal closes.


exec overwrites the running process with a new process image. So, in your current process, the shell you're running is overwritten by the ls executable image, and once ls exits, the process is shut down.