本文介绍了在 bash 中循环元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 bash 中循环元组?

Is it possible to loop over tuples in bash?

举个例子,如果以下内容有效,那就太好了:

As an example, it would be great if the following worked:

for (i,j) in ((c,3), (e,5)); do echo "$i and $j"; done

是否有一种解决方法可以让我遍历元组?

Is there a workaround that somehow lets me loop over tuples?

推荐答案

$ for i in c,3 e,5; do IFS=","; set -- $i; echo $1 and $2; done
c and 3
e and 5

关于 set 的这种使用(来自 man builtins):

About this use of set (from man builtins):

选项处理后剩余的任何参数都被视为值对于位置参数,并按顺序分配给 $1、$2、... $n

IFS="," 设置字段分隔符,因此每个 $i 都被分割为 $1$2> 正确.

The IFS="," sets the field separator so every $i gets segmented into $1 and $2 correctly.

通过本博客.

更正确的版本,正如@SLACEDIAMOND 所建议的:

more correct version, as suggested by @SLACEDIAMOND:

$ OLDIFS=$IFS; IFS=','; for i in c,3 e,5; do set -- $i; echo $1 and $2; done; IFS=$OLDIFS
c and 3
e and 5

这篇关于在 bash 中循环元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:25