203
145

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 5 years have passed since last update.

[bash] 実行スクリプトの絶対パスの取得

Last updated at Posted at 2017-05-19

毎回調べてるので使い方メモ

スクリプトの配置位置、実行位置を気にせずにスクリプトの実行をしたい
相対パスから絶対パスへの変換に使用する

実装

スクリプトの絶対パスの取得
SCRIPT_DIR=$(cd $(dirname $0); pwd)
  • $0 で実行コマンドを取得
  • dirname でベースディレクトリを取得
  • サブシェル内で cd で移動
  • pwd で絶対パスの取得

使用例

test.sh
#!/bin/bash

SCRIPT_DIR=$(cd $(dirname $0); pwd)

echo $SCRIPT_DIR
使用例
$ ./test.sh
/tmp

$ mkdir hoge
$ cd hoge/
$ ../test.sh
/tmp

どこから実行してもパスは変化しない

203
145
0

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
203
145

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?