带有通配符和隐藏文件的 Bash for 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2135770/
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 21:35:02  来源:igfitidea点击:

Bash for loop with wildcards and hidden files

bashloopsscriptingwildcard

提问by sixtyfootersdude

Just witting a simple shell script and little confused:

只是知道一个简单的 shell 脚本并且有点困惑:

Here is my script:

这是我的脚本:

% for f in $FILES; do echo "Processing $f file.."; done

The Command:

命令:

ls -la | grep bash 

produces:

产生:

% ls -a | grep bash
.bash_from_cshrc
.bash_history
.bash_profile
.bashrc

When

什么时候

FILES=".bash*"

I get the same results (different formatting) as ls -a. However when

我得到与 ls -a 相同的结果(不同的格式)。然而当

FILES="*bash*"

I get this output:

我得到这个输出:

Processing *bash* file..

This is not the expected output and not what I expect. Am I not allowed to have a wild card at the beginning of the file name? Is the . at the beginning of the file name "special" somehow?

这不是预期的输出,也不是我所期望的。文件名的开头不允许有通配符吗?是个 。在文件名“特殊”的开头不知何故?

Setting

环境

FILES="bash*"

Also does not work.

也不起作用。

采纳答案by gregseth

FILES=".bash*"works because the hidden files name begin with a .

FILES=".bash*"有效,因为隐藏文件名以 .

FILES="bash*"doesn't work because the hidden files name begin with a .not a b

FILES="bash*"不起作用,因为隐藏文件名以.not a开头b

FILES="*bash*"doesn't work because the *wildcard at the beginning of a string omits hidden files.

FILES="*bash*"不起作用,因为*字符串开头的通配符省略了隐藏文件。

回答by nos

The default globbing in bash does not include filenames starting with a . (aka hidden files).

bash 中的默认通配符不包括以 . (又名隐藏文件)。

You can change that with

你可以用

shopt -s dotglob

shopt -s dotglob

$ ls -a
.  ..  .a  .b  .c  d  e  f
$ ls *
d  e  f
$ shopt -s dotglob
$ ls *
.a  .b  .c  d  e  f
$ 

To disable it again, run shopt -u dotglob.

要再次禁用它,请运行shopt -u dotglob.

回答by ghostdog74

If you want hidden and non hidden, set dotglob (bash)

如果你想隐藏和非隐藏,设置 dotglob (bash)

#!/bin/bash
shopt -s dotglob
for file in *
do
 echo "$file"
done

回答by alanc

Yes, the .at the front is special, and normally won't be matched by a *wildcard, as documented in the bash man page (and common to most Unix shells):

是的,.前面的 是特殊的,通常不会与*通配符匹配,如 bash 手册页中所述(并且对大多数 Unix shell 很常见):

When a pattern is used for pathname expansion, the character “.” at the start of a name or immediately following a slash must be matched explicitly, unless the shell option dotglobis set. When matching a pathname, the slash character must always be matched explicitly. In other cases, the “.” character is not treated specially.

当模式用于路径名扩展时,字符“.” 除非设置了 shell 选项dotglob,否则在名称的开头或紧跟在斜杠之后必须显式匹配 。匹配路径名时,斜杠字符必须始终明确匹配。在其他情况下,“。” 字符没有特殊处理。