How to set relative paths by file, not by path criteria for entering commands?

Asked 2 years ago, Updated 2 years ago, 96 views

The title is weird because I don't know it well.

The result depends on where the command written in the shell script runs the script. For example:

#!/bin/sh
pwd

Scripts like this

home
  p parent
      ch Child
          test.sh

When running in the same folder structure as above,

Actual execution results:

The results change like this. Can't we fix the results based on the path where the actual file is located, regardless of where the file runs (except for the absolute path with environmental variables)?

desired execution result:

So that you get this result.

To give a more specific example,

home
  p parent
      ch Child
           test.sh
      s script
           execute-me.sh
#!/bin/sh
../script/execute-me.sh
#!/bin/sh
echo hello world!

When the path and content of the file are the same as above, I want to make sure that the result is the same no matter which path I run test.sh. As it stands, if you don't run test.sh from home/parent/child, you won't find execute-me.sh.

Of course Instead of ../script/execute-me.sh, you can write /home/parent/script/execute-me.sh as the absolute path, but this is not what I want. Is there any other way?

bash shell shell-script unix linux

2022-09-22 08:45

2 Answers

There's something like this.

#!/bin/sh
dirpath=`dirname $0`
echo $dirpath 
cd $dirpath
pwd


2022-09-22 08:45

export WORK_HOME=/home/.../...
WORK_HOME/script.sh 

It's common to deal with it like above.


2022-09-22 08:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.