执行命令,如Bash的字符串 [英] Execute command as a string in Bash
问题描述
我测试一个简短的bash脚本。我想执行字符串命令。
#!/斌/庆典回声AVR-GCC
$精灵=main.elf
$ C =$的main.c
$ GCC =AVR-GCC -mmcu = ATmega128的-Wall -Os -o $精灵$ C
EVAL $ GCC
回声AVR-GCC做
我知道这是丑陋的,所有的,但它不应该执行AVR-GCC命令?
这些错误有以下几种:
./ AVR.sh:4号线:= main.elf:命令未找到
./AVR.sh:5号线:= .C:命令未找到
./AVR.sh:6号线:= AVR-GCC -mmcu = ATmega128的-Wall -Os -o:命令未找到
我不知道你的最终目标是什么,但你可能会改为考虑使用以下更可靠的方法:使用数组在bash。 (我不打算讨论你在你的脚本有几个语法错误。)
不要把你的命令及其参数的字符串像你一样,然后评估
字符串(顺便说一句,你的情况中,eval也没用)。我理解你的脚本(这个版本不会给你你所提到的错误,比较您的版本,特别是有对变量赋值没有美元符号):
#!/斌/庆典回声AVR-GCC
精灵=main.elf
C =main.c中
GCC =AVR-GCC -mmcu = ATmega128的-Wall -Os -o $精灵$ C
EVAL $ GCC
回声AVR-GCC做
您会很快遇到问题的时候,比如你遇到空格或搞笑的符号文件(觉得一个名为的;室射频*
)。相反:
#!/斌/庆典回声AVR-GCC
精灵=main.elf
C =main.c中
GCC =AVR-GCC
选项=(-mmcu = ATmega128的-Wall - OS)
命令=($ GCC$ {选项[@]}-o$小精灵,$ C)
#执行:
$ {命令[@]}
试着了解是怎么回事(我可以澄清任何具体点,你会问我),并意识到它是多么安全不是将命令字符串。
I'm testing a short bash script. I'd like to execute a string as a command.
#!/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"
I know it's ugly and all, but shouldn't it execute the avr-gcc command? The errors are the following:
./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
I don't know what your final goal is, but you might instead consider using the following more robust way: using arrays in bash. (I'm not going to discuss the several syntax errors you have in your script.)
Don't put your commands and its argument in a string as you did and then eval
the string (btw, in your case, the eval is useless). I understand your script as (this version will not give you the errors you mentioned, compare with your version, especially there are no dollar signs for variable assignments):
#!/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"
You'll very soon run into problems when, for example, you encounter files with spaces or funny symbols (think of a file named ; rm -rf *
). Instead:
#!/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[@]}"
Try to understand what's going on here (I can clarify any specific points you'll ask me to), and realize how much safer it is than putting the command in a string.
这篇关于执行命令,如Bash的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!