bash Shell脚本:检查文件是文件而不是目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4804239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:20:21  来源:igfitidea点击:

Shell script: Check that file is file and not directory

bashfileshelldirectory

提问by Industrial

I'm currently working on a small cute shell script to loop through a specific folder and only output the files inside it, excluding any eventual directories. Unfortunately I can't use findas I need to access the filename variables.

我目前正在编写一个小巧可爱的 shell 脚本来循环遍历特定文件夹并只输出其中的文件,不包括任何最终目录。不幸的是,我无法使用,find因为我需要访问文件名变量。

Here's my current snippet, which doesn't work:

这是我当前的片段,它不起作用:

for filename in "/var/myfolder/*"
do
  if [ -f "$filename" ]; then
    echo $filename # Is file!
  fi

done;

What am I doing wrong?

我究竟做错了什么?

回答by SirDarius

You must not escape /var/myfolder/*, meaning, you must remove the double-quotes in order for the expression to be correctly expanded by the shell into the desired list of file names.

您不能转义 /var/myfolder/*,这意味着您必须删除双引号,以便 shell 将表达式正确扩展为所需的文件名列表。

回答by Fred Foo

What you're doing wrong is not using find. The filename can be retrieved by using {}.

你做错的是没有使用find. 可以使用 检索文件名{}

find /var/myfolder -maxdepth 1 -type f -exec echo {} \;

回答by sarnold

for filename in "/var/myfolder/*"

for filename in "/var/myfolder/*"

The quotes mean you get one giant string from that glob -- stick an echo _ $filename _immediately before the ifto discover that it only goes through the 'loop' once, with something that isn't useful.

引号意味着你从那个 glob 中得到一个巨大的字符串——echo _ $filename _在 之前贴上一个if,发现它只通过“循环”一次,有些东西没有用。

Remove the quotes and try again :)

删除引号并重试:)

回答by vmpstr

Try without double quotes around /var/myfolder/* (reason being is that by putting double quotes you are making all the files a single string instead of each filename a separate string

尝试在 /var/myfolder/* 周围不使用双引号(原因是通过放置双引号,您将所有文件变成一个字符串,而不是每个文件名变成一个单独的字符串

回答by Noufal Ibrahim

You can use find and avoid all these hassles.

您可以使用 find 并避免所有这些麻烦。

for i in $(find /var/myfolder -type f)
do
echo $(basename $i)
done

Isn't this what you're trying to do with your situation? If you want to restrict depth, use the -maxdepthoption to find.

这不是你试图对你的情况做的事情吗?如果要限制深度,请使用-maxdepth查找选项。