Read glob from command line in Bash

后端 未结 3 1172
失恋的感觉
失恋的感觉 2020-12-10 15:38

How do I read a glob in Bash from command line? I tried this and it only picks up the first file in the glob:

#!/bin/bash
shopt -s nullglob
FILES=$1
for f in         


        
相关标签:
3条回答
  • 2020-12-10 15:49

    You need to access all the contents of the parameters that are passed to the script. The glob is expanded by the shell before your script is executed.

    You could copy the array:

    #!/bin/bash
    FILES=("$@")
    for f in "${FILES[@]}"
    do
        echo "Processing $f file..."
        echo "$f"
    done
    

    Or iterate directly:

    #!/bin/bash
    for f     # equivalent to for f in "$@"
    do
        echo "Processing $f file..."
        echo "$f"
    done
    

    Or use shift:

    #!/bin/bash
    while (($# > 0))
    do
        echo "Processing $1 file..."
        echo "$1"
        shift
    done
    
    0 讨论(0)
  • 2020-12-10 16:03

    The reason it reads only the first file, is that the pattern /home/hss/* gets expanded before it is passed as an argument to your script. So your script does not see it as a pattern, but as a list of files, matching that glob.

    So, you need to call it like eugene y specified in his post:

    sh script.sh "/home/hss/*" 4 gz
    

    The quoting of $1 looks optional to me. It just makes the pattern to expand in for cycle rather than in assignment.

    0 讨论(0)
  • 2020-12-10 16:09

    You need to quote any parameters which contain shell meta-characters when calling the script, to avoid pathname expansion (by your current shell):

    sh script.sh "/home/hss/*" 4 gz
    

    Thus $1 will be assigned the pattern and not the first matched file.

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