LoginSignup
22
12

More than 5 years have passed since last update.

ディレクトリの中身の有無によって条件分岐をしたい

Last updated at Posted at 2016-11-20

ディレクトリが空ディレクトリかどうかによって条件分岐を行いたいということがよくあると思います。たとえば「対象のディレクトリがファイルやディレクトリを有しているとき、その中身をすべて削除する」という処理は次のように書くことができます。

directory=/hoge/hoge
if [ -n "$(ls $directory)" ]; then
    rm -r $directory
fi

-nは引数が空文字以外ならtrueを、それ以外ならfalseを返します。対象のディレクトリが空のときlsは何も返さず、したがってそれを文字列化した"$(ls $directory)"が空文字となるため、[ -z $(ls $directory) ]がtrueとなりifの本体が実行されるというわけです。

ちなみに-z-nの逆、つまり引数が空文字ならtrueを、それ以外ならfalseを返します。次の例ではディレクトリが空かどうかをみて、空ならばそのディレクトリ直下にcsvファイルを配置するという処理を行っています。

directory =/foo/foo
if [ -z "$(ls $directory)" ]; then
    touch directory/foo.csv
fi
22
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
12