【问题标题】:How do I iterate through positional variables in bash?如何遍历 bash 中的位置变量?
【发布时间】:2017-07-07 16:42:40
【问题描述】:

用户将给出他们想要的任意数量的位置参数(这些都是 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  

【问题讨论】:

  • 您能否详细说明“不工作”部分? 如何它不起作用?请花一些时间到read about how to ask good questions
  • 我不完全理解你想要达到的目标,但我很肯定Makefile 可能会做得更好。
  • 它一直给我一个语法错误 echo for (i=3; i> 编译,通常我在做什么工作?
  • 您需要在回显时引用所有特殊字符,例如 &lt;。此外,您需要在 if 语句中的 = 周围留有空格。
  • 我正在尝试在另一个脚本中创建一个 bash 脚本,该脚本将编译给定的任何 c 程序

标签: c linux bash unix ubuntu


【解决方案1】:

不要使用一堆echo 语句,使用here-doc。在 &lt;&lt; 之后的标记周围加上引号可防止扩展 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() 行中的 &lt;,所以您遇到了错误。

其他错误:在[ 命令中,= 周围需要空格,而在for 循环的末尾缺少done。而要间接访问变量,则需要使用${!var} 语法。

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

for arg

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

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

【讨论】:

  • 我想这样做,以便命令将附加到另一个脚本(因为我试图在另一个脚本中编写它),有没有我可以这样做?
  • 你没在脚本的第一行看到&gt;&gt;compile吗?
  • ./compile: line 4: syntax error near unexpected token (' ./compile: line 4: for (i=3; i
  • @zee 这种类型的for循环需要((...))
  • 我添加了另一种循环所有参数的方法。
【解决方案2】:

以下是我将如何编辑您最初发布的内容:

$ cat test.sh
echo -e "#!/bin/bash" > compile.sh
echo -e "if [ \"\${1}\" == \"-o\" ]; then" >> compile.sh
echo -e "\tlist_of_arguments=\${@:3} #puts all arguments starting with \$3 into one argument" >> compile.sh
echo -e "\tfor i in \${list_of_arguments}; do" >> compile.sh
echo -e "\t\techo \"gcc \${1} '\${2}' '\${i}'\"" >> compile.sh
echo -e "\tdone" >> compile.sh
echo -e "fi" >> compile.sh
$ ./test.sh
$ cat compile.sh
#!/bin/bash
if [ "${1}" == "-o" ]; then
        list_of_arguments=${@:3} #puts all arguments starting with $3 into one argument
        for i in ${list_of_arguments}; do
                echo "gcc ${1} '${2}' '${i}'"
        done
fi
$ chmod +x compile.sh
$ ./compile.sh -o one two three four five
gcc -o 'one' 'two'
gcc -o 'one' 'three'
gcc -o 'one' 'four'
gcc -o 'one' 'five'

出于演示目的,我在test.sh 中回应了gcc 命令。要实际运行 gcc 而不是回显它,请将 test.sh 中的第五行从:

echo -e "\t\techo \"gcc \${1} '\${2}' '\${i}'\"" >> compile.sh

echo -e "\t\tgcc \${1} '\${2}' '\${i}'" >> compile.sh

或者像这样通过管道将 echo 传递给 sh:

echo -e "\t\techo \"gcc \${1} '\${2}' '\${i}'\" \| sh" >> compile.sh

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    相关资源
    最近更新 更多