gpt4 book ai didi

linux - 如何在命令中插入循环

转载 作者:太空宇宙 更新时间:2023-11-04 06:05:03 26 4
gpt4 key购买 nike

例如:命令(--option * 4次)

我可以在这里使用for循环吗?请建议!

换句话说

command --option1 --option2 --option3 --option3 --option3

所以我想要循环中的选项3。

最佳答案

参见BashFAQ #50讨论为什么解决这个问题的天真的尝试经常失败(或者最初看起来有效,但当利用更有趣的数据或更有问题的场景时却失败了)。

谨慎遵循最佳实践的方法可能如下所示:

#!/usr/bin/env bash

number_of_option3s=4
args=( )
for ((i=0; i<number_of_option3s; i++)); do
args+=( --option3 )
done

your_command --option1 --option2 "${args[@]}"

大概在现实世界的用例中,您需要修改 args+=( --option="$i") 或迭代文件名并执行类似 for file in *.txt; 的操作;执行 args+=( --input "$file");完成;所有这些都会起作用。

<小时/>

如果您不使用 bash 运行而是需要使用 /bin/sh,这会变得更难看:

#!/bin/sh

# need to use a function since there's only one array, "$@", but it has a separate
# instance per stack depth.
call_with_repeated_option() {
number_of_options=$1; shift
option_to_append=$1; shift
i=0
while [ "$i" -lt "$number_of_options" ]; do
set -- "$@" "$option_to_append"
i=$((i + 1))
done
"$@"
}

# call your_command with 4 "--option3" arguments after --option1 and --option2
call_with_repeated_option 4 --option3 your_command --option1 --option2

关于linux - 如何在命令中插入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48876379/

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