gpt4 book ai didi

c - 我如何遍历 bash 中的位置变量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:59 24 4
gpt4 key购买 nike

用户将给出他们想要的任意数量的位置参数(这些都是 C 程序)。我想让所有的 C 程序都能编译。但是,这是行不通的;有没有人有解决办法?

echo '#!/bin/bash' >> compile  
echo if [ "-o"='$1' ] >> compile
echo then >> compile
echo for (i=3; i<='$#'; i++) >> compile
echo do >> compile
echo gcc -o '$2' '${i}' >> compile
echo fi >> compile

最佳答案

不要使用一堆 echo语句,请使用 here-doc。在 << 之后在 token 周围加上引号防止在 here-doc 中扩展变量。

cat <<'EOF' >>compile
'#!/bin/bash'
if [ "-o" = "$1" ]
then
for ((i=3; i <= $#; i++))
do
gcc -o "$2" "${!i}"
done
fi
EOF

否则,您需要转义或引用所有特殊字符——您收到错误是因为您没有转义 <for()行。

其他错误:= 两边需要空格在[命令,你错过了donefor 的末尾环形。要间接访问变量,您需要使用 ${!var}语法。

遍历所有参数的常用方法是使用一个简单的:

for arg

循环。当没有 in 时在 for variable 之后,它循环遍历参数。您只需要删除 -o outputfile参数优先:

output=$2
shift 2 # remove first 2 arguments
for arg
do
gcc -o "$output" "$arg"
done

关于c - 我如何遍历 bash 中的位置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310069/

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