[A-00051]Shellでファイル存在チェック

シェルスクリプトを利用してファイルの存在チェックを行う方法を記載する。

#!/bin/bash

if [[ -e test.txt ]];
then
  echo "test.txt is exist."
else
  echo "test.txt is not exist."
fi

カレントディレクトリは下記のとおり。test.txtは存在しないので偽の判定結果となる。

anonymous-MacBook-Pro:test$ ls
callFunc.sh		sjis.csv		test4.sh
date.txt		test.csv		test5.sh
date.txt.bak		test.sh			unitseparator.csv
echeck.sh		test2.sh		unitseparator.txt
func.sh			test3.sh		utf.csv
sample.csv		test4.log
anonymous-MacBook-Pro:test$ . echeck.sh 
test.txt is not exist.

ファイルリストから該当するファイルが存在するかチェックする

応用として例えばテキストファイルに記載されるファイルが存在するかどうかをチェックするプログラムを記載しておく。

ファイルリストは下記のとおり

callFunc.sh
date.txt
func.sh
lsif.txt      #存在しない
notex.csv     #存在しない
sjis.csv
anonymous.log #存在しない
test4.log

whileループで上記のファイルから一行づつ読み込んでそのファイルが存在するかをチェックする。

#!/bin/bash

while read file
do

if [[ -e $file ]];
then
  echo "$file is exist."
else
  echo "$file is not exist."
fi

done < ./files.list

存在しないファイルはnot existとなり、想定どおりの結果となった。

anonymous-MacBook-Pro:test$ ./echeck.sh 
callFunc.sh is exist.
date.txt is exist.
func.sh is exist.
lsif.txt is not exist.
notex.csv is not exist.
sjis.csv is exist.
anonymous.log is not exist.
test4.log is exist.

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

*