Bash > ファイルやディレクトリの存在をチェックする方法
更新日
2012-11-16
広告
Bashで、ファイルやディレクトリの存在を確認する方法を紹介します。
if testによる確認方法
ファイルやディレクトリの存在を確認するには、以下の構文を使います。if [ -e パス ]; then # 存在する場合 else # 存在しない場合 fi「パス」の部分に、チェックしたいファイルやディレクトリのパスを指定します。 (実際は、testコマンドを実行することになります。)
ファイルtest.txtと、ディレクトリtestdirを用意した状態で、サンプルcheck.shを実行してみます。
以下はサンプルです。
test-check-file$ ls check.sh test.txt testdircheck.shの内容は以下のとおりです。
#!/bin/bash file=test.txt dir=testdir # test.txtが存在するかチェック if [ -e $file ]; then echo "$file found." else echo "$file NOT found." fi # testdirが存在するかチェック if [ -e $dir ]; then echo "$dir found." else echo "$dir NOT found." ficheck.shの実行結果は、以下のとおりです。
test-check-file$ ./check.sh test.txt found. testdir found.
ファイルかディレクトリかの確認
パスで指定される内容が、ファイルなのか、ディレクトリなのかをチェックすることもできます。オプション | チェックの内容 |
---|---|
-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これの実行結果は以下のようになります。
test-check-file$ ./check.sh test.txt is a file. testdir is NOT a file. test.txt is NOT directory. testdir is a directory.びっくりマーク(!)を使うと、真偽を反転できます。
#!/bin/bash file=test.txt if [ ! -e $file ]; then echo "$file NOT found." else echo "$file found." fi if [ ! -f $file ]; then echo "$file is NOT a file." else echo "$file is a file." fi実行すると以下のようになります。
test-check-file$ ./check2.sh test.txt found. test.txt is a file.
ワイルドカードを指定してファイルを確認
ファイル名にワイルドカードを指定して、ファイルを確認したい場合があります(例えば、'.txt'という拡張子を持つファイルが存在するか?など)。この場合は、以下のようにします。if ls *.txt > /dev/null 2>&1 then echo "exists" fi'*.txt'なファイルが存在すれば、'ls *.txt'は何らかの文字列を返すので、if文の判定は「真」となります。 '*.txt'なファイルが存在しない場合はエラーが発生するので、それは /dev/null にリダイレクトしています。
広告
お問い合わせは sweng.tips@gmail.com まで。