3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2021-02-23

bash のスクリプトで絶対パスを取得するときはどうするんだっけ?
などと思って、Google検索などをすると、cd して pwd するスクリプトを紹介する古い記事が上位にヒットする。
以下は、実行した shell スクリプト(この場合は bash)が置かれているディレクトリを変数DIRにセットする例。

スクリプト例
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 ならオプションの指定で実在しないディレクトリも指定できます。デフォルトでは実在しないディレクトリではエラーを返します。

3
1
1

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
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?