Bash glob参数仅显示第一个文件,而不显示所有文件 [英] Bash glob parameter only shows first file instead of all files

查看:55
本文介绍了Bash glob参数仅显示第一个文件,而不显示所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要运行此cmd行脚本

  $ script.sh lib/* ../test_git_thing 

我希望它处理/lib文件夹中的所有文件.

  FILES = $ 1对于$ FILES中的f做回声正在处理$ f文件..."完毕 

当前它仅打印第一个文件.如果我使用$ @,它会给我所有文件,但会提供我不需要的最后一个参数.有什么想法吗?

解决方案

在bash和ksh中,您可以迭代除最后一个参数以外的所有参数,例如:

  for"$ {@:1:$#-1}"中的f;做回声"$ f"完毕 

在zsh中,您可以执行类似的操作:

  for $ @ [1,$ {#}-1]中的f;做回声"$ f"完毕 

$#是参数的数量, $ {@:start:length} 是bash和ksh中的子字符串/子序列符号,而 $ @ [start,end] 是zsh中的子序列.在所有情况下,下标表达式都被视为算术表达式,这就是 $#-1 起作用的原因.(在zsh中,您需要 $ {#}-1 ,因为 $#-被解释为" $-的长度".)/p>

在所有三个shell中,您可以将 $ {x:start:length} 语法与标量变量一起使用,以提取子字符串.在bash和ksh中,可以将 $ {a [@]:start:length} 与数组一起使用以提取值的子序列.

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?

解决方案

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.

这篇关于Bash glob参数仅显示第一个文件,而不显示所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆