如何在bash中编写循环,执行如下操作:
for (i=0; i< len("$@"); i+=2) {
print a[i], a[i+1]
// do stuff using the pair elements.
}
答案 0 :(得分:4)
简单(和POSIX兼容)方法不是索引到$@
,而是在开始时简单地将事情移开:
while [ "$#" -gt 0 ]; do
echo "$1, $2"
shift; shift
done
如果您确实想要编制索引,并且不介意特定于shell(如bash)采用ksh开创的扩展:
# start at 1 to avoid $0
# quotes in immediately below line because SO syntax highlighter doesn't know bash
for ((i=1; i<("$#" + 1); i+=2)); do
echo "${@:i:1}, ${@:i+1:1}"
done