LoginSignup
26

More than 5 years have passed since last update.

posted at

updated at

bash で ファイルの絶対パスを得る

bash で ファイルの絶対パスを得る必要があり、調査してみた。

参考

See

方法1

1.sh
#!/bin/bash
abspath=$(cd $(dirname $1) && pwd)/$(basename $1)
echo ${abspath}

実行例

$ ./1.sh 1.sh
/Users/katoy/tools/1.sh

$ ./1.sh /usr/local/bin/ack
/usr/local/bin/ack

$ ./1.sh /tmp
//tmp

/tmp となって欲しいけど, //tmp になってしまうなぁ ...

方法2

2.sh
#!/bin/bash
abspath=`greadlink -f $1`
echo ${abspath}

greadlink は brew install coreutils でインストールできる。

実行例

$ ./2.sh 2.sh
/Users/katoy/tools/2.sh

$ ./2.sh /usr/local/bin/ack
/usr/local/Cellar/ack/2.12/bin/ack

$ ./2.sh /tmp
/private/tmp

//tmp となることはない。 
/tmp でなく、シンボリックリンク先が得られる。 まあそのほうが都合が良いかもしれない。

方法3

すこし行数が多くなるけど。

3.sh
#!/bin/bash

# See http://unix.stackexchange.com/questions/101080/realpath-command-not-found
realpath ()
{
    f=$@;
    if [ -d "$f" ]; then
        base="";
        dir="$f";
    else
        base="/$(basename "$f")";
        dir=$(dirname "$f");
    fi;
    dir=$(cd "$dir" && /bin/pwd);
    echo "$dir$base"
}

echo $(realpath $1)

実行例

$ ./3.sh 3.sh
/Users/katoy/tools/3.sh

$ ./3.sh /usr/local/bin/ack
/usr/local/Cellar/ack/2.12/bin/ack

$ ./3.sh /tmp
/tmp

この方法では //tmp のようになることはない。

求む 他の実装

/tmp に対して /tmp が得られる簡単な実装は無いだろうか?
情報がえられれば、この投稿を編集して更新していきたいと思います。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
26