6
How do I get the path to the directory in which the script in bash is located within the script?
#!/bin/bash
MINHADIR="caminho/para/onde/estou" # apanhar a diretoria onde estou atualmente
6
How do I get the path to the directory in which the script in bash is located within the script?
#!/bin/bash
MINHADIR="caminho/para/onde/estou" # apanhar a diretoria onde estou atualmente
5
I don’t know if this answers the question but:
#!/bin/bash
echo "A script está em: $0"
echo "O invocador está em $PWD"
Update 1 print the absolute path of the script
To get the absolute path, we start by merging the current directory with
the directory of the script ( $PWD "=" dirname $0 "/"
).
Then we rewrite (in this case using perl) the cases where q directory
script is a relative path (./d
../../b
b/c
) using replacements.
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
0
Perhaps a more general solution is:
#!/bin/bash
PROGNAME=$(basename $0)
PROGDIR=$(readlink -m $(dirname $0))
This also works for directories with links.
Browser other questions tagged bash directory
You are not signed in. Login or sign up in order to post.
More or less that, that is, the
$0
is returning the path I used to access and execute the script, already the$PWD
is returning the path where I am. The idea would be, regardless of where I am, to get the path from script, example:O seu _script_ está localizado em: /home/zuul/bash/
, which is different from path used to execute it, example:O caminho utilizado para aceder ao script foi: ../../bash/
. Note: If unclear, it warns that I edit the question to clarify the idea.– Zuul
@Zuul, the implicit answer in my answer was:
dirname $0
(can be absolute or relative). I assume therefore that you need the absolute path. Right? There is also the question of possible existences of symbolic links etc. that I propose to ignore.– JJoao
Yes, absolute and symbolic ignored... Imagine the case where we intend to work with files in the location of script.
– Zuul
@Zuul, please see if this update makes sense.
– JJoao