Bash glob parameter only shows first file instead of all files

后端 未结 4 775
遇见更好的自我
遇见更好的自我 2020-12-12 08:36

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.

<         


        
4条回答
  •  情歌与酒
    2020-12-12 08:46

    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.

提交回复
热议问题