在Bash中以字符串形式执行命令

erb*_*bal 11 linux bash

我正在测试一个简短的bash脚本.我想将一个字符串作为命令执行.

#!/bin/bash

echo "AVR-GCC"
$elf=" main.elf"
$c=" $main.c"
$gcc="avr-gcc -mmcu=atmega128 -Wall -Os -o $elf$c"
eval $gcc
echo "AVR-GCC done"
Run Code Online (Sandbox Code Playgroud)

我知道它很丑陋,但不应该执行avr-gcc命令吗?错误如下:

./AVR.sh: line 4: = main.elf: command not found
./AVR.sh: line 5: = .c: command not found
./AVR.sh: line 6: =avr-gcc -mmcu=atmega128 -Wall -Os -o : command not found
Run Code Online (Sandbox Code Playgroud)

gni*_*urf 17

我不知道你的最终目标是什么,但你可以考虑使用以下更强大的方法:在bash中使用数组.(我不打算讨论脚本中的几个语法错误.)

不要像你那样把你的命令及其参数放在字符串中,然后eval是字符串(顺便说一句,在你的情况下,eval是没用的).我理解你的脚本为(这个版本不会给你提到的错误,与你的版本相比,特别是没有变量赋值的美元符号):

#!/bin/bash

echo "AVR-GCC"
elf="main.elf"
c="main.c"
gcc="avr-gcc -mmcu=atmega128 -Wall -Os -o $elf $c"
eval $gcc
echo "AVR-GCC done"
Run Code Online (Sandbox Code Playgroud)

例如,当您遇到带空格或有趣符号的文件时(考虑一个名为的文件; rm -rf *),您很快就会遇到问题.代替:

#!/bin/bash

echo "AVR-GCC"
elf="main.elf"
c="main.c"
gcc="avr-gcc"
options=( "-mmcu=atmega128" "-Wall" -"Os" )
command=( "$gcc" "${options[@]}" -o "$elf" "$c" )
# execute it:
"${command[@]}"
Run Code Online (Sandbox Code Playgroud)

试着了解这里发生了什么(我可以澄清你要求我提出的任何具体要点),并意识到将命令放在一个字符串中要多安全一些.

  • 非常感谢你!:)我完全理解你的解决方案. (2认同)

Som*_*ude 5

创建变量时,只有在访问变量时才使用美元视线.

所以改变

$elf=" main.elf"
$c=" $main.c"
$gcc="avr-gcc -mmcu=atmega128 -Wall -Os -o $elf$c"
Run Code Online (Sandbox Code Playgroud)

elf=" main.elf"
c=" $main.c"
gcc="avr-gcc -mmcu=atmega128 -Wall -Os -o $elf$c"
Run Code Online (Sandbox Code Playgroud)