Check whether a certain file type/extension exists

2019-03-08 22:54发布

How would you go about telling whether files of a specific extension are present in a directory, with bash?

Something like

if [ -e *.flac ]; then 
echo true; 
fi 

标签: linux bash shell
13条回答
虎瘦雄心在
2楼-- · 2019-03-08 23:09
shopt -s nullglob
if [[ -n $(echo *.flac) ]]    # or [ -n "$(echo *.flac)" ]
then 
    echo true
fi
查看更多
萌系小妹纸
3楼-- · 2019-03-08 23:11

For completion, with zsh:

if [[ -n *.flac(#qN) ]]; then
  echo true
fi

This is listed at the end of the Conditional Expressions section in the zsh manual. Since [[ disables filename globbing, we need to force filename generation using (#q) at the end of the globbing string, then the N flag (NULL_GLOB option) to force the generated string to be empty in case there’s no match.

查看更多
爷的心禁止访问
4楼-- · 2019-03-08 23:14
#/bin/bash

myarray=(`find ./ -maxdepth 1 -name "*.py"`)
if [ ${#myarray[@]} -gt 0 ]; then 
    echo true 
else 
    echo false
fi
查看更多
别忘想泡老子
5楼-- · 2019-03-08 23:15

This uses ls(1), if no flac files exist, ls reports error and the script exits; othewise the script continues and the files may be be processed

#! /bin/sh
ls *.flac  >/dev/null || exit
## Do something with flac files here
查看更多
三岁会撩人
6楼-- · 2019-03-08 23:17
#!/bin/bash
files=$(ls /home/somedir/*.flac 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
echo "Some files exists."
else
echo "No files with that extension."
fi
查看更多
Evening l夕情丶
7楼-- · 2019-03-08 23:21

Here's a fairly simple solution:

if [ "$(ls -A | grep -i \\.flac\$)" ]; then echo true; fi

As you can see, this is only one line of code, but it works well enough. It should work with both bash, and a posix-compliant shell like dash. It's also case-insensitive, and doesn't care what type of files (regular, symlink, directory, etc.) are present, which could be useful if you have some symlinks, or something.

查看更多
登录 后发表回答