[SOLVED] bash script - return full path and filename
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
How about this one to get absolute path? Simpler, even local variables are not needed. Little modification will get you the file base name if needed, as soon as you can define its behaviour when you give directory as argument (should it be the last directory or empty string?).
Code:
function abspath {
if [[ -d "$1" ]]
then
pushd "$1" >/dev/null
pwd
popd >/dev/null
elif [[ -e $1 ]]
then
pushd $(dirname $1) >/dev/null
echo $(pwd)/$(basename $1)
popd >/dev/null
else
echo $1 does not exist! >&2
return 127
fi
}
function getabspath {
local -a T1 T2
local -i I=0
local IFS=/ A
case "$1" in
/*)
read -r -a T1 <<< "$1"
;;
*)
read -r -a T1 <<< "/$PWD/$1"
;;
esac
T2=()
for A in "${T1[@]}"; do
case "$A" in
..)
[[ I -ne 0 ]] && unset T2\[--I\]
continue
;;
.|'')
continue
;;
esac
T2[I++]=$A
done
case "$1" in
*/)
[[ I -ne 0 ]] && __="/${T2[*]}/" || __=/
;;
*)
[[ I -ne 0 ]] && __="/${T2[*]}" || __=/.
;;
esac
}
Calling a binary from a bash script can sometimes be preferred. Here's some C code which can be compiled using gcc -Wall -o getpath getpath.c
Code:
// getpath.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Getpath takes one filename or directory as a parameter\n");
exit (1);
}
char AbsPath[strlen(argv[1] + 1)];
realpath(argv[1],AbsPath);
printf("%s\n",AbsPath);
return 0;
}
So if desired, copy the code above to a plain text file called getpath.c and compile it. Then use "./getpath <filename>" If you put getpath is in your path somewhere, the ./ can be omitted.
Last edited by Andy Alkaline; 07-08-2011 at 08:02 AM.
Reason: code revision
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.