Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a script in the same directory as the current script

I have two Bash scripts in the same folder (saved somewhere by the user who downloads the entire repository):

  • script.sh is run by the user
  • helper.sh is required and run by script.sh

The two scripts should be in the same directory. I need the first script to call the second one, but there are two problems:

  1. Knowing the current working directory is useless to me, because I don't know how the user is executing the first script (could be with /usr/bin/script.sh, with ./script.sh, or it could be with ../Downloads/repo/scr/script.sh)
  2. The script script.sh will be changing to a different directory before calling helper.sh.

I can definitely hack together Bash that does this by storing the current directory in a variable, but that code seems needlessly complicated for what I imagine is a very common and simple task.

Is there a standard way to reliably call helper.sh from within script.sh? And will work in any Bash-supported operating system?

like image 519
IQAndreas Avatar asked Aug 16 '16 15:08

IQAndreas


People also ask

How do I reliably open files in the same folder?

The best and most reliable way to open a file that's in the same directory as the currently running Python script is to use sys. path[0]. It gives the path of the currently executing script. You can use it to join the path to your file using the relative path and then open that file.

How do I refer to a current directory in bash?

Print Current Working Directory ( pwd ) To print the name of the current working directory, use the command pwd . As this is the first command that you have executed in Bash in this session, the result of the pwd is the full path to your home directory.


1 Answers

Since $0 holds the full path of the script that is running, you can use dirname against it to get the path of the script:

#!/bin/bash  script_name=$0 script_full_path=$(dirname "$0")  echo "script_name: $script_name" echo "full path: $script_full_path" 

so if you for example store it in /tmp/a.sh then you will see an output like:

$ /tmp/a.sh script_name: /tmp/a.sh full path: /tmp 

so

  1. Knowing the current working directory is useless to me, because I don't know how the user is executing the first script (could be with /usr/bin/script.sh, with ./script.sh, or it could be with ../Downloads/repo/scr/script.sh)

Using dirname "$0" will allow you to keep track of the original path.

  1. The script script.sh will be changing to a different directory before calling helper.sh.

Again, since you have the path in $0 you can cd back to it.

like image 89
fedorqui 'SO stop harming' Avatar answered Oct 01 '22 20:10

fedorqui 'SO stop harming'