Reputation:
I want to execute a bash script in the current shell, not a subshell/subprocess. I believe using exec
allows you to do that.
But if I run:
exec ./my_script.sh
the shell will exit and it will say "process completed". Is there a way to execute a script in the same shell somehow w/o exiting the process.
note the only thing my_script.sh does is:
export foo=bar
but if there was some error in my script, it didn't appear in the console.
Upvotes: 0
Views: 4046
Reputation: 817
man page says:-
exec [-cl] [-a name] [command [arguments]] If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command.This is what login(1) does. The -c option causes command to be executed with an empty environment.
if you want to execute a bash script in the current shell,you can try
bash my_script.sh or ./my_script.sh
Upvotes: 0
Reputation: 718788
As @Snakienn has said, you can / should use the "." builtin command to "source" the file containing commands; e.g.
. ./my_script.sh
What this does is to temporarily change where the shell is reading commands from. Commands and other shell input are read from the file as if they were being read from the terminal. When the shell gets to the end-of-file, it switches back to taking input from the console.
This is called "sourcing". (Not "execing".) And indeed the shell accepts source
as an alternative name for the .
command.
The exec
command does something completely different. As the bash
manual entry says:
exec [-cl] [-a name] [command [arguments]]
If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command.
The concept and terminology of exec
comes from early UNIX (i.e Unix V6 or earlier) where the syscalls for running a child command were fork
and exec
. The procedure was:
fork
the current process creating a clone of current process (the child)exec
the new commandUpvotes: 3
Reputation: 619
you can try . ./my_script.sh
.
The first dot stands for the current shell.
Upvotes: 1