Jamis Charles Jamis Charles - 7 months ago 45
Bash Question

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.

for f in $FILES
echo "Processing $f file..."

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?


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

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

In zsh, you can do something similar:

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

$# 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.