How to run a shell script inside a shell script

I am using bash on Mac OSX.

I have a shell file named myshell.sh and I use it to do a lot of things.

I have a entrance.sh file which contains:

# content of entrance.sh
./myshell.sh arg1 arg2
./myshell.sh arg3 arg4

But when I run entrance.sh I got a error:

./entrance.sh: line 2: myshell.sh: command not found

I can run the myshell.sh directly.

What can I do?

Asked By: AGamePlayer

||

As suggested by YoMismo you should use full path in your script or cd to your scripts directory.

# content of entrance.sh
/full/path/myshell.sh arg1 arg2
/full/path2/myshell.sh arg3 arg4

Or (but this is a very ugly solution)

# content of entrance.sh
cd /full/path
./myshell.sh arg1 arg2
cd /full/path2
./myshell.sh arg3 arg4
Answered By: Kiwy

./myshell.sh means the script myshell.sh is found in the current directory. If you run this script from somewhere else, it won’t work. You could use full paths, but in this case, the only sensible solutions are:

  1. Adding the location of myshell.sh to your $PATH (in case, myshell.sh really is something that is supposed to be called from everywhere). So, add PATH="$PATH":/dir/of/myshell at the beginning of the outer script.

  2. Put myshell.sh somewhere so that it’s accessible from everywhere (just like all other executables on the system). That would be /usr/local/bin most likely. Use this only if this script is universally useful.

If the scripts rely on local files in their directory (and may even break down and do damage if called from elsewhere), then you should either leave it in the current form (this actually prevents you to call them from places you are not supposed to), or use cd inside the script to get to the proper location. Be careful, use absolute paths in shell scripts for cd, it is too easy to break stuff if something goes wrong and you go out .. and cd-ing further in fails, you could escape out of your directory and reign chaos all over the parent directories.

Mostly I’d recommend solution #1.

Answered By: orion

My guess is that ./myshell.sh does not have execute permissions (need to perform ‘chmod +x myshell.sh’), or is not in the current directory (need to move it to the same directory as entrance.sh).

Try calling ./myshell from the same directory as ./entrance.sh, do you get the same result?

Also, if you want to be more certain that you run your script you can call bash directly on it:

/bin/bash ./myshell arg1 arg2
Answered By: Centimane
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.