サンプル集?
ファイルやディレクトリの存在をチェックする
if testによる確認方法
ファイルやディレクトリの存在を確認するには、以下の構文を使います。
if [ -e パス ]; then
# 存在する場合
else
# 存在しない場合
fi
ファイルかディレクトリかの確認
パスで指定される内容が、ファイルなのか、ディレクトリなのかをチェックすることもできます。
- -f パスで指定される内容がファイルかどうか
- -d パスで指定される内容がディレクトリかどうか
#!/bin/bash
file=test.txt dir=testdir
# test.txtはファイルかどうかをチェック
if [ -f $file ]; then
echo "$file is a file."
else
echo "$file is NOT a file."
fi
# testdirはファイルかどうかをチェック
if [ -f $dir ]; then
echo "$dir is a file."
else
echo "$dir is NOT a file."
fi
# test.txtはディレクトリかどうかをチェック
if [ -d $file ]; then
echo "$file is a directory."
else
echo "$file is NOT directory."
fi
# testdirはディレクトリかどうかをチェック
if [ -d $dir ]; then
echo "$dir is a directory."
else
echo "$dir is NOT a directory."
fi