Bash, know what directory is running

6

How do I get the directory path where the script in bash is located, from inside the script itself?

#!/bin/bash

MINHADIR="caminho/para/onde/estou" # apanhar a diretoria onde estou atualmente
    
asked by anonymous 13.04.2015 / 23:52

2 answers

5

I do not know if this answers the question further:

#!/bin/bash
echo "A script está em: $0"
echo "O invocador está em $PWD"

Update 1 print the absolute script path

To get the absolute path, we start by joining the current directory with the script directory ( $PWD "=" dirname $0 "/" ).

Then we rewrite (in this case using perl) the cases where q of the script is a relative path ( ./d ../../b b/c ) using overrides.

So:

#!/bin/bash
printf "%s=%s/" $PWD 'dirname $0' |         # formatar como "$PWD=$0/"
    perl -pe 'while(s!/[^/]+=\.\./!=!){};   # a/b=../c --> a=c
              s!.*=/|=\./?!=! ;             # a/b=/c --> =c ;  b=./c => b=c 
              s!=!/!; '

or even

#!/bin/bash
script_dir=$(printf .......e mais as outras 3 linhas... )    
echo $script_dir
    
14.04.2015 / 00:13
0

Perhaps a more general solution is:

#!/bin/bash
PROGNAME=$(basename $0)
PROGDIR=$(readlink -m $(dirname $0))

This also works for directories with links.

    
01.06.2015 / 22:29