Call one shell script from another script using relative paths

I have a script like this:

#!/bin/csh echo "This is the main programme" ./printsth 

I want to call printsth script from this script using relative paths. Is there any way to do this? By relative paths, I mean the path relative to my script call.

+6
source share
2 answers

You can access the current working directory with $cwd . Therefore, if you want to call printsth with the path to the current working directory, run the line with $cwd .

For example, if you want to call printsth in the current directory, say:

 $cwd/printsth 

If you want to call printsth one directory above:

 $cwd/../printsth 

Make sure this is a csh script (i.e. first line #!/bin/csh ). If it's a sh or bash script, you need to use $PWD (for a "real working directory"), not $cwd .

EDIT:

If you need a directory related to the script directory and not the current working directory, you can do this:

 setenv SCRIPTDIR `dirname $0` $SCRIPTDIR/printsth 

This will install $SCRIPTDIR in the same directory as the source script. Then you can create paths regarding this.

+4
source

Running a script like ./printsth will not always work, since the relative path will depend on the directory from which the main script was run.

One solution would be to make sure that we go into the directory in which the script is present, and then run it:

 cd -P -- "$(dirname -- "$0")" ./printsth 

For more examples, see How to set the current working directory to a script directory?

See also: How to convert an absolute path to a relative path?

0
source

Source: https://habr.com/ru/post/957322/


All Articles