LoginSignup
0
0

More than 5 years have passed since last update.

bash のスクリプトが環境変数でパスが通ったディレクトリにいるか確認・判断する(カレントディレクトリ)

Last updated at Posted at 2018-10-21

macOS や RaspberryPi(Raspbian)のシェル・スクリプト(bash)で、スクリプトのディレクトリがパスの通ったディレクトリにあるか確認したいのです。

bash カレント ディレクトリ 環境変数 パス 確認」と Qiita 記事に絞ってググっても出てこなかったので、俺様ググラビリティの備忘録として。

TL;DR

環境変数のパス($PATH)を配列で取得してループ処理

bash
#!/bin/bash

# 環境変数のパスを配列で取得
IFS=: eval 'list_path=($PATH)'

# 配列をループ
for e in "${list_path[@]}"; do
    if [ $e = $SCRIPT_DIR ] ; then
        echo $e
    fi
done

TS;DR

使いやすいように関数化してみました。もっとスッキリした書き方がある気もします。

bash
#!/bin/bash

is_pwd_in_path() {
    IFS=: eval 'LIST_PATH=($PATH)'
    DIR_SCRIPT=$(cd $(dirname $0); pwd)

    for e in "${LIST_PATH[@]}"; do
        if [ $e = $DIR_SCRIPT ] ; then
            return 0
        fi
    done

    return $BASH_LINENO
}

if is_pwd_in_path ; then
    echo 'Is in path'
else
    echo 'Not in path'
fi

動作確認済み環境

  • macOS HighSierra(OSX 10.13.6)
    • bash --version: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17)
  • Raspbian GNU/Linux 8 (jessie)
    • bash --version: GNU bash, バージョン 4.3.30(1)-release (arm-unknown-linux-gnueabihf)

参考文献

0
0
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
0
0