Search code examples
bashshellglob

Bash glob parameter only shows first file instead of all files


I want to run this cmd line script

$ script.sh   lib/* ../test_git_thing

I want it to process all the files in the /lib folder.

FILES=$1
for f in $FILES
do
  echo "Processing $f file..."
done

Currently it only prints the first file. If I use $@, it gives me all the files, but also the last param which I don't want. Any thoughts?


Solution

  • In bash and ksh you can iterate through all arguments except the last like this:

    for f in "${@:1:$#-1}"; do
      echo "$f"
    done
    

    In zsh, you can do something similar:

    for f in $@[1,${#}-1]; do
      echo "$f"
    done
    

    $# is the number of arguments and ${@:start:length} is substring/subsequence notation in bash and ksh, while $@[start,end] is subsequence in zsh. In all cases, the subscript expressions are evaluated as arithmetic expressions, which is why $#-1 works. (In zsh, you need ${#}-1 because $#- is interpreted as "the length of $-".)

    In all three shells, you can use the ${x:start:length} syntax with a scalar variable, to extract a substring; in bash and ksh, you can use ${a[@]:start:length} with an array to extract a subsequence of values.