Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix shell scripting: pass shell options (-x etc.) to nested scripts

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.

like image 250
nodakai Avatar asked Oct 19 '22 16:10

nodakai


1 Answers

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

like image 51
Nicolae Avatar answered Oct 21 '22 09:10

Nicolae