9

I have a script like this:

#!/bin/csh
echo "This is the main programme"
./printsth

I want to call the script printsth from within this script using relative paths. Is there a way to do so? By relative paths I mean path relative to where my calling script is.

Programmer
  • 6,565
  • 25
  • 78
  • 125
  • 1
    why do you think this isn't working? Learn to turn on your shell debugging, ie `set -vx` (or similar for csh) AND `echo $cwd` etc to see where you are at. Good luck. – shellter Nov 04 '13 at 22:39

2 Answers2

9

You can refer to the current working directory with $cwd. So if you want to call printsth with a path relative to the current working directory, start the line with $cwd.

For example, if you want to call the printsth in the current directory, say:

$cwd/printsth

If you want to call the printsth one directory above:

$cwd/../printsth

Be sure it's a csh script though (ie. the first line is #!/bin/csh). If it's an sh or bash script, you need to use $PWD (for 'present working directory'), not $cwd.

EDIT:

If you want a directory relative to the script's directory, not the current working directory, then you can do this:

setenv SCRIPTDIR `dirname $0`
$SCRIPTDIR/printsth

That will set $SCRIPTDIR to the same directory as the original script. You can then build paths relative to that.

Joe Z
  • 17,413
  • 3
  • 28
  • 39
  • can you do this without using $cwd and $pwd – Programmer Nov 04 '13 at 08:10
  • Well, actually, the default for `csh` is to use the current working directory any way, so `./printsth` will look in CWD anyway. If you want to look in the same directory as the original script, that's actually a little harder. Which is it you want? – Joe Z Nov 04 '13 at 08:13
  • I want to look in the same directory as orig script – Programmer Nov 04 '13 at 08:16
  • In MacOS w/ ZSH at least, `setenv` isn't a thing, but you can use `SCRIPTDIR=\`dirname $0\`` – mltsy Apr 12 '23 at 16:34
3

Running script as ./printsth won't work always, as relative path would depend on directory from which the main script has been run.

One solution would be to make sure that we enter the directory where the script is present, then run it:

cd -P -- "$(dirname -- "$0")"
./printsth

For more examples, see: How to set current working directory to the directory of the script?

See also: How to convert absolute path into relative path?

Community
  • 1
  • 1
kenorb
  • 155,785
  • 88
  • 678
  • 743