0

I've been working on a script but always with a fixed directory (/opt/mw/script). I need to change that to be able to execute the script from any directory.
I think I will need to add a "." at the beginning of the line to be able to execute the script?
For example ./mw/script

Is this correct?

Thanks

radicaled
  • 1,499
  • 4
  • 21
  • 34
  • I also need to put the script in any path. – radicaled Mar 09 '15 at 14:46
  • If you need to have the script in any path without using the absolute file path you can put the directory in your PATH variable.Look [here](http://www.troubleshooters.com/linux/prepostpath.htm). Also be careful as you can cause quite a few problems if you get it wrong, –  Mar 09 '15 at 14:58

2 Answers2

1

You already can execute that script from any directory with that absolute file path. It's the relative file paths (that start with ./ or ../) that can only be executed from a specific directory.

Paul Evans
  • 26,111
  • 3
  • 30
  • 50
  • Excellent, thanks. But I also need to be able to put the script in any path. Sorry, I think I forgot to put it in the comments – radicaled Mar 09 '15 at 14:45
  • So make all your paths relative to the script directory *in* the script itself and execute your script with an absolute file path. – Paul Evans Mar 09 '15 at 17:16
0

You need to add the "." if the script is in the current directory (e.g. ./script), but it is optional if the script is already inside another directory (e.g. mw/script).

Also notice that if your script contains relative references to other files and directories, you may need to use this trick to properly refer to them from any directory.

For instance, consider the following script using absolute paths:

#!/bin/bash

# lists all files in this directory
ls /opt/mw

If it is converted to relative paths as follows:

#!/bin/bash

# lists all files in this directory
ls mw

Then this script will only work if you run it from its own directory (e.g. cd /opt/ && ./script).

But then you can generalize it like this:

#!/bin/bash

SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
# lists all files in this directory
ls $SCRIPT_DIR/mw

Now the script works even when executed from another directory.

Community
  • 1
  • 1
anol
  • 6,712
  • 1
  • 27
  • 68