gpt4 book ai didi

bash - 一次循环多个项目

转载 作者:行者123 更新时间:2023-11-29 08:50:40 26 4
gpt4 key购买 nike

我们可以遍历一组项目,一次考虑一个项目,如下所示:

#!/bin/bash
for i in $( ls ); do
echo item: $i
done

我们如何在类似的循环中一次处理多个项目?像这样的东西:

#!/bin/bash
for i,j,k in $( ls ); do
echo item i: $i
echo item j: $j
echo item k: $k
done

第二个 shell 脚本不正确,但应该准确说明我要实现的目标。

最佳答案

假设您没有太多的项目(尽管 shell 应该能够处理相当多的位置参数。

# Save the original positional arguments, if you need them
original_pp=( "$@" )
set -- *
while (( $# > 0 )); do
i=$1 j=$2 k=$3 # Optional; you can use $1, $2, $3 directly
...
shift 3 || shift $# # In case there are fewer than 3 arguments left
done

# Restore positional arguments, if necessary/desired
set -- "${original_pp[@]}"

为了 POSIX 兼容性,请使用 [ "$#"-gt 0 ] 而不是 ((...)) 表达式。没有简单的方法来以 POSIX 兼容的方式保存和恢复所有位置参数。 (除非有一个字符可以用来将它们明确地连接成一个字符串。)

这是 jm666 提到的子 shell:

(
set -- *
while [ "$#" -gt 0 ]; do
i=$1 j=$2 k=$3
...
shift 3 || shift $#
done
)

一旦子 shell 退出,您在子 shell 中设置的任何参数更改都将丢失,但以上代码在其他方面与 POSIX 兼容。

关于bash - 一次循环多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25814250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com