Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2885

絶対パスの取得には realpath を使おう

$
0
0

bash のスクリプトで絶対パスを取得するときはどうするんだっけ?
などと思って、Google検索などをすると、cd して pwd するスクリプトを紹介する古い記事が上位にヒットする。

スクリプト例
DIR=$(cd$(dirname$0);pwd)

古いディストリビューションを使わざるをえない場合や、実行環境に依存しないスクリプトを書かなければいけない場合にはこの方法もいいだろうが、最近のディストリビューションには普通に realpath というコマンドがインストールされているはずなので、こちらを使いましょう。

realpathを使った例
DIR=$(realpath$(dirname$0))

GNU coreutilsに含まれているものなので、RedHat系でも Ubuntu でも最小構成のインストールに含まれているはず。

Usage: realpath [OPTION]... FILE...
Print the resolved absolute file name;
all but the last component must exist

  -e, --canonicalize-existing  all components of the path must exist
  -m, --canonicalize-missing   no path components need exist or be a directory
  -L, --logical                resolve '..' components before symlinks
  -P, --physical               resolve symlinks as encountered (default)
  -q, --quiet                  suppress most error messages
      --relative-to=DIR        print the resolved path relative to DIR
      --relative-base=DIR      print absolute paths unless paths below DIR
  -s, --strip, --no-symlinks   don't expand symlinks
  -z, --zero                   end each output line with NUL, not newline

      --help     display this help and exit
      --version  output version information and exit

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation at: <https://www.gnu.org/software/coreutils/realpath>
or available locally via: info '(coreutils) realpath invocation'

pwd を使うスクリプトの場合は、実在するディレクトリじゃないと駄目ですが、realpath ならオプションの指定で実在しないディレクトリも指定できます。デフォルトでは実在しないディレクトリではエラーを返します。


Viewing all articles
Browse latest Browse all 2885

Trending Articles