Reputation: 8021
How can I run nested shell scripts with the same option? For example,
parent.sh
#!/bin/sh
./child.sh
child.sh
#!/bin/sh
ls
How can I modify parent.sh
so that when I run it with sh -x parent.sh
, the -x
option is effective in child.sh
as well and the execution of ls
is displayed on my console?
I'm looking for a portable solution which is effective for rare situations such as system users with /bin/false
as their registered shell. Will the $SHELL
environment variable be of any help?
Clarification: I sometimes want to call parent.sh
with -x
, sometimes with -e
, depending on the situation. So the solution must not involve hard-coding the flags.
Upvotes: 5
Views: 792
Reputation: 6960
it's looks like a hack and seems it's not the best way.
But it will do exact what you want
One of the ways how you can do it - it's to create aliases to create wrappers for sh
:
alias saveShell='cp /bin/sh $some_safe_place'
alias shx='cp $some_safe_place /bin/x_sh; rm /bin/sh; echo "/bin/x_sh -x $@" > /bin/sh; chmod 755 /bin/sh '
alias she='cp $some_safe_place /bin/e_sh; rm /bin/sh; echo "/bin/e_sh -e $@" > /bin/sh; chmod 755 /bin/sh '
alias restoreShell='cp $some_safe_place /bin/sh'
How to Use:
run saveShell
and then use shx
or she
, if you would change -x
on -e
run restoreShell
and then run shx
or she
run script as usually
sh ./parent.sh
BE VERY CAREFUL WITH MOVING SH
Other solution
replace #!/bin/sh
to #!/bin/sh -x
or #!/bin/sh -e
with sed
in all sh files before running script.
Upvotes: 0
Reputation: 451
If you use bash
, i can recommend the following:
#!/bin/bash
export SHELLOPTS
./child.sh
You can propagate as many times as you need, also you can use echo $SHELLOPTS
in every script down the line to see what is happening and how options are propagated if you need to understand it better.
But for /bin/sh
it will fail with /bin/sh: SHELLOPTS: readonly variable
because of how POSIX is enforced on /bin/sh
in various systems, more info here: https://lists.gnu.org/archive/html/bug-bash/2011-10/msg00052.html
Upvotes: 3