Bash(shell)でディレクトリ・ファイルの存在チェックをする

ファイルの存在チェック

if [ -f "sample.txt" ]; then
    echo 'file exist'
else
    echo 'file not exist'
fi

ディレクトリの存在チェック

if [ -d "sample_dir" ]; then
    echo 'dir exist'
else
    echo 'dir not exist'
fi

ディレクトリが存在しなかったら作成する


DIR_PATH="sample_dir"

if [ ! -d "$DIR_PATH" ]; then
    mkdir -p $DIR_PATH
fi

[ ] -f オプション

ファイルが存在する場合、True。存在しない場合、False。

[ ] -d オプション

ディレクトリが存在する場合、True。存在しない場合、False。