Re: bash: relative to absolute path
From: Shea Martin (smartin_at_arcis.com)
Date: 01/11/05
- Next message: david_kirby_byers_at_yahoo.com: "unix peripheral units"
- Previous message: Pascal Bourguignon: "Re: bash: relative to absolute path"
- In reply to: Pascal Bourguignon: "Re: bash: relative to absolute path"
- Next in thread: Grumble: "Re: bash: relative to absolute path"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 10 Jan 2005 19:53:56 -0700
Pascal Bourguignon wrote:
> Shea Martin <smartin@arcis.com> writes:
>
>
>>I often need to get the absolute path of a file in my bash scripts.
>>I started to device a path parser, but then found this cheezy but
>>simple solution. Does anyone have a more efficient/better solution?
>>[...]
>> DIR=$(cd "$DIR" && pwd && cd $OLDPWD)
>>[...]
>
>
> You don't need to go back to the old directory since $(...) forks a
> sub-shell that cannot change the working directory of the parent shell.
>
> DIR=$(cd "$DIR" && pwd)
Thanks, I should have known that.
>
> Given that a file may not have a _unique_ absolute path, this is as
> good as any other method to find an absolute path for a file. I don't
> think you can get any better.
>
>
I just realized that my current implementation will only work on existing files.
here is one that is more flexible, though maybe not as simple or efficient.
~S
<code>
rel2abs()
{
# make sure file is specified
if [ -z "$1" ]
then
echo "$0 <path>"
return 1
fi
# already absolute case
if [ "${1:0:1}" = "/" ] || [ "$PWD" = "/" ]
then
ABS=""
else
ABS="$PWD"
fi
# loop thru path
IFS="/"
for DIR in $1
do
if [ -n "$DIR" ]
then
if [ "$DIR" = ".." ]
then
ABS="${ABS%/*}"
elif [ "$DIR" != "." ]
then
ABS="$ABS/$DIR"
fi
fi
done
IFS=":"
echo $ABS
return 0
}
</code>
- Next message: david_kirby_byers_at_yahoo.com: "unix peripheral units"
- Previous message: Pascal Bourguignon: "Re: bash: relative to absolute path"
- In reply to: Pascal Bourguignon: "Re: bash: relative to absolute path"
- Next in thread: Grumble: "Re: bash: relative to absolute path"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]