[关闭]
@ysongzybl 2015-05-06T20:05:59.000000Z 字数 651 阅读 6567

Check if a file exists with wildcard in shell script

bash


  1. if ls /path/to/your/files* 1> /dev/null 2>&1; then
  2. echo "files do exist"
  3. else
  4. echo "files do not exist"
  5. fi

Or better one:

  1. for f in /path/to/your/files*; do
  2. ## Check if the glob gets expanded to existing files.
  3. ## If not, f here will be exactly the pattern above
  4. ## and the exists test will evaluate to false.
  5. [ -e "$f" ] && echo "files do exist" || echo "files do not exist"
  6. ## This is all we needed to know, so we can break after the first iteration
  7. break
  8. done

For example, I want to remove all files with name prefix "aabb" at current foler, then I write script as:

  1. for f in ./aabb*; do
  2. if [ -e "$f" ];
  3. then
  4. rm $f
  5. fi
  6. done

Reference

http://stackoverflow.com/questions/6363441/check-if-a-file-exists-with-wildcard-in-shell-script

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注