Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is different between running a program directly and calling exec in script?

Tags:

linux

exec

What is the difference between running a program with exec command or not ?

For instance, If I made a script file like below.

#script1
python test.py

#script2
exec python test.py

Both seem to return the same result.

Are they equivalent?

like image 695
SangminKim Avatar asked Mar 13 '23 21:03

SangminKim


1 Answers

exec is a shell built-in, which replaces the image of the current process with new process. It's not same as calling a binary/executable.

To see the difference, do:

#script1
python test.py
echo Hello

#script2
exec python test.py
echo Hello

You will not see the Hello getting printed in the second script.

exec also another purpose in shells. It can be used for redirection. For example,

exec 1>file

redirects the stdout of the process to file.

If you had:

exec 1>file
echo hello 
echo world

then script would redirect hello and world to file instead of stdout.

like image 173
P.P Avatar answered Apr 07 '23 17:04

P.P