Home > Net >  Bash - running script as it was executed in its own folder
Bash - running script as it was executed in its own folder

Time:09-02

I have a bash script called my-script.sh inside a folder 2 level up from the root where I want this script to be called/executed from

/folder1
    /folder2/
        - my-script.sh
        - do-it.sh

my-script.sh

#!/bin/bash
./do-it.sh

If I execute my-script.sh from the root folder it fails since it tries to find do-it.sh in the same folder.

folder1/folder2/my-script.sh: line 3: ./do-it.sh: No such file or directory

If I want to execute my-script.sh script properly I have to get into folder2 first and them execute it

cd /folder1/folder2
./my-script.sh

Is there a way to execute it from root folder as it was being executed from folder2?

CodePudding user response:

To make my scripts run anywhere I usually add this line to get the folder containing the script

script_folder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
$script_folder/my-script.sh

CodePudding user response:

I found a short and simple solution using dirname $0

my-script.sh

#!/bin/bash
./$(dirname $0)/do-it.sh

CodePudding user response:

The simplest way to run a script from a certain directory is simply by mentioning the directory when running the script, so in your case:

Where-ever you are, you want to run the script as present in the /folder1/folder2 folder:

sh /folder1/folder2/my-script.sh

Where-ever you are, you want to run the script as present in the root folder:

sh /my-script.sh

As far as the do-it.sh is concerned: you can create a do-it.sh in your root folder, containing the following:

#!/bin/bash
sh /folder1/folder2/do-it.sh
  • Related