在 shell 脚本中迭代地传递一组文件中的一个文件作为命令行参数

Iteratively pass one file from a collection of files as command line parameters in shell script

我有 x 个文件:A、B、C... 我需要做的是将这些文件中的每一个作为python 文件的第一个命令行参数,并将其他参数作为第二个命令行参数传递,直到所有文件都作为 $1 传递一次。例如,在第一次迭代中 A 是 $1,B,C... 是 $2。在第二次迭代中,B 是 $1,A,C... 是 $2。我已经在 shell 中阅读了 shift 命令,但我不太确定它是否适用于我的情况(我对 shell 脚本编写也比较陌生).另外,我可以传递给 python 脚本的命令行参数的数量是否有限制?我还想在遍历我的文件之前创建一个变量来保存文件名列表。谢谢!

Bash 有数组,并通过 ${array[@]:start:end} 语法支持数组切片,其中 startend 是可选索引。这足以完成工作。

#!/bin/bash

# Store the master list of file names in an array called $files.    
files=("$@")

for ((i = 0; i < ${#files[@]}; ++i)); do
    # Store the single item in $file and the rest in an array $others.
    file=${files[i]}
    others=("${files[@]:0:i}" "${files[@]:i+1}")

    # Run command.py. Use ${others[*]} to concatenate all the file names into one long
    # string, and override $IFS so they're joined with commas.
    (IFS=','; command.py "${files[i]}" "${others[*]}")
done