【求助】有什么方法实现定位shell脚本本身所在的绝对路径吗?

请dearvoid快快指导.如果没问题能不能把这个贴加个精华      
[QUOTE=mxx823]
#!/bin/bash
#
# file: who_am_i.sh
#

rundir=$PWD
cmd=$0
cmd=${cmd##*/}
echo "$rundir/$cmd"

以上是我的解决方案,请dearvoid过目.
[/QUOTE]
引用:
-(guest@mac:tty1)-(root)-
[3714 0] % pwd
/root
-(guest@mac:tty1)-(root)-
[3714 0] % cat ./tmp/foo.sh
#!/bin/bash
#
# file: who_am_i.sh
#

rundir=$PWD
cmd=$0
cmd=${cmd##*/}
echo "$rundir/$cmd"
-(guest@mac:tty1)-(root)-
[3714 0] % ./tmp/foo.sh
/root/foo.sh          <--- should be "/root/tmp/foo.sh"
-(guest@mac:tty1)-(root)-
[3714 0] %


      
不好意思。被dearvoid这个老小子又快了一步,我来删帖子都来不及。
实在是太佩服dearvoid。不过我会很快进步,争取打败dearvoid这个老小子。
大家支持我。      
dearvoid大人。我继续向你叫板,第一指出你的脚本的问题。如下:
[root@localhost /]# ~/../home/hjf/who_am_i.sh
/who_am_i.sh
看这个结果爽不爽?:w      
上面看完了没?

怎么样?受不了了吧。好。那么且听下回分解。      
which version were you using?
引用:
-(guest@mac:tty1)-(/)-
[3714 0] % pwd
/
-(guest@mac:tty1)-(/)-
[3714 0] % cat /home/hjf/where_am_i.sh
#!/bin/bash
#
# file: who_am_i.sh
#

rundir=$PWD
cmd=$0

if [ "$cmd" = "${cmd/\//}" ]; then
    command which $cmd
    exit 0
fi

if [ ${cmd:0:1} = / ]; then
    pathname=$cmd
else
    pathname="$rundir/$cmd"
fi
name=$(basename $pathname)
path=$(dirname $pathname)
cd "$path"
if [ "$PWD" = / ]; then
    echo "/$name"
else
    echo "$PWD/$name"
fi
-(guest@mac:tty1)-(/)-
[3714 0] % ~/../home/hjf/where_am_i.sh
/home/hjf/where_am_i.sh
-(guest@mac:tty1)-(/)-
[3714 0] % cd /home/hjf/
-(guest@mac:tty1)-(hjf)-
[3714 0] % PATH=$PATH:.
-(guest@mac:tty1)-(hjf)-
[3714 0] % where_am_i.sh
/home/hjf/where_am_i.sh
-(guest@mac:tty1)-(hjf)-
[3714 0] %


      
好了。我不跟dearvoid老小子玩了。:w 我把我的代码附下。
请dearvoid老大人过目。
代码:[QUOTE]
#!/bin/bash
#who_am_i.sh

cmd=$0
if [ "$cmd" = "${cmd/\//}" ] ;then
command which $cmd
exit 0
fi

name=$(basename $cmd)
path=$(dirname $cmd)
cd "$path"
echo "$PWD/$name"







[/QUOTE]       
dearvoid在不在?赶紧过目,先把那张帖子的精华去掉。不要让哪个再骗人了。
精华加这个上面吧。给我加300分吧。:w      
[QUOTE=mxx823]好了。我不跟dearvoid老小子玩了。:w 我把我的代码附下。
请dearvoid老大人过目。
代码: [/QUOTE]
引用:
-(guest@mac:tty1)-(/)-
[28638 0] % pwd
/
-(guest@mac:tty1)-(/)-
[28638 0] % cat /foo.sh
#!/bin/bash
#who_am_i.sh

cmd=$0
if [ "$cmd" = "${cmd/\//}" ] ;then
   command which $cmd
   exit 0
fi

name=$(basename $cmd)
path=$(dirname $cmd)
cd "$path"
echo "$PWD/$name"
-(guest@mac:tty1)-(/)-
[28638 0] % /foo.sh
//foo.sh          <--- should be "/foo.sh"
-(guest@mac:tty1)-(/)-
[28638 0] %


      
我抄错了。不管怎么样就是又臭又长。看我的吧。
把精华加我那里吧。^_^