ひとり勉強ログ

ITエンジニアの勉強したことメモ

#09 ファイル属性を評価する演算子

-e file file が存在する
-d file file が存在し、ディレクトリである
-h file file が存在し、シンボリックリンクである
-L file file が存在し、シンボリックリンクである
-f file file が存在し、通常ファイルである
-r file file が存在し、読み取りパーミッションが与えられている
-w file file が存在し、書き込みパーミッションが与えられている
-x file file が存在し、実行パーミッションが与えられている
file1 -nt file2 file の変更時刻が file2 より新しい
file1 -ot file2 file の変更時刻が file2 より古い

ファイル属性を評価する例

Vimで「if-dir.sh」というファイル名を作成、以下を記述、実行権限を付与する。 [bash]

!/bin/bash

logdirectory=/home/minecraft/logs/

if [ -d "$logdirectory" ]; then echo "ログディレクトリは: $logdirectory" else echo "[ERROR] ログディレクトリはありません: $logdirectory" fi [/bash]

変数「logdirectory」に「/home/minecraft/logs/」を格納。 変数「logdirectory」が存在し、かつディレクトリであれば「ログディレクトリは: /home/minecraft/logs/」と表示される。

シェルスクリプトを実行する

[bash] $ ./if-dir.sh [/bash] 実行結果。 [bash] [ERROR] ログディレクトリはありません: [/bash]

「logs」ディレクトリを作成後、再度実行すると以下のように表示される。 [bash] ログディレクトリは: /home/minecraft/logs/ [/bash]