0

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?

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Very neat solution. You may want to consider to cd $script_folder before executing my-script.sh, as then the context of my-script.sh is also inside folder2
I think you meant $script_folder/do-it.sh
1

I found a short and simple solution using dirname $0

my-script.sh

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

1 Comment

This is a simplified version of my answer above, it should mostly work. Be careful though : your version can break in a number of cases, see this other post stackoverflow.com/questions/59895/…
0

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

1 Comment

I don't want edit the script if files are moved to another directory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.