LoginSignup
0
1

More than 3 years have passed since last update.

testコマンドでワイルドカードを含むpathを評価したい

Posted at

検証環境

  • Windows10 Pro 1903
  • WSL(Ubuntu)
  • bash 4.4.20
root@mycomputer:~# bash --version
GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
root@mycomputer:~#

検証

ワイルドカードをtestに渡すと、(そのpathで表せるファイルなどが存在する場合は)エラーになる

root@mycomputer:~# ll /tmp/{hoge,fuga}/*
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/fuga/1.log
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/fuga/2.log
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/hoge/1.log
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/hoge/2.log
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/hoge/3.log
root@mycomputer:~#
root@mycomputer:~# [ -f /tmp/fuga/*.log ] ; echo $? # binary operator expectedエラー
-bash: [: /tmp/fuga/1.log: binary operator expected
2
root@mycomputer:~#

# 余談だが、全く存在しないpathであればtestできる
root@mycomputer:~# [ -f /tmp/fuga/*.txt ] ; echo $? 
1
root@mycomputer:~#

ワイルドカードを含むpathをtestしたい時はfor文を使う。forの変数(以下例の場合target)にはワイルドカードが展開された後の値が格納されるので、testの評価対象がワイルドカードを含まなくなり、エラーが出ない。

root@mycomputer:~# ll /tmp/{hoge,fuga}/*
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/fuga/1.log
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/fuga/2.log
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/hoge/1.log
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/hoge/2.log
-rw-rw-rw- 1 root root 0 Aug 24 23:13 /tmp/hoge/3.log
root@mycomputer:~#
root@mycomputer:~# target_arr=(
>   "/tmp/hoge/?.log"
>   "/tmp/fuga/*.log"
>   "/tmp/fuga/*.txt"
> )
root@mycomputer:~# for target in ${target_arr[@]} ; do
>   echo ${target}
>   [ -f ${target} ] ; echo $?
> done
/tmp/hoge/1.log # /tmp/hoge/?.log の1つ目
0
/tmp/hoge/2.log # /tmp/hoge/?.log の2つ目
0
/tmp/hoge/3.log # /tmp/hoge/?.log の3つ目
0
/tmp/fuga/1.log # /tmp/fuga/*.log の1つ目
0
/tmp/fuga/2.log # /tmp/fuga/*.log の2つ目
0
/tmp/fuga/*.txt # /tmp/fuga/*.txt。存在しないので1
1
root@mycomputer:~#

なおbrace展開 ({} を用いたpath指定) は上記の限りではない。forの変数に展開済みのpathを格納したくてもbraceだと展開されないようだ。

root@mycomputer:~# target_arr=(
>   "/tmp/{hoge,fuga}/1.log"
> )
root@mycomputer:~# for target in ${target_arr[@]} ; do
>   echo ${target}
> done
/tmp/{hoge,fuga}/1.log # 展開されていない
root@mycomputer:~#
0
1
0

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
0
1