Bash for loop with wildcards and hidden files

后端 未结 4 1655
Happy的楠姐
Happy的楠姐 2020-12-10 00:41

Just witting a simple shell script and little confused:

Here is my script:

% for f in $FILES; do echo \"Processing $f file..\"; done
<
相关标签:
4条回答
  • 2020-12-10 01:15

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

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

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

    0 讨论(0)
  • 2020-12-10 01:22

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

    You can change that with

    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.

    0 讨论(0)
  • 2020-12-10 01:28

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

    #!/bin/bash
    shopt -s dotglob
    for file in *
    do
     echo "$file"
    done
    
    0 讨论(0)
  • 2020-12-10 01:42

    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):

    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 dotglob is set. When matching a pathname, the slash character must always be matched explicitly. In other cases, the “.” character is not treated specially.

    0 讨论(0)
提交回复
热议问题