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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19786149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:16:22  来源:igfitidea点击:

Execute command as a string in Bash

linuxbash

提问by erbal

I'm testing a short bash script. I'd like to execute a string as a command.

我正在测试一个简短的 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"

I know it's ugly and all, but shouldn't it execute the avr-gcc command? The errors are the following:

我知道这很丑陋,但它不应该执行 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

采纳答案by gniourf_gniourf

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.)

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

Don't put your commands and its argument in a string as you did and then evalthe 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):

不要像之前那样将命令及其参数放在字符串中,然后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"

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:

例如,当您遇到带有空格或有趣符号的文件(想想名为 的文件; 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[@]}"

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.

试着理解这里发生了什么(我可以澄清你要我做的任何具体点),并意识到它比将命令放在字符串中要安全得多。

回答by Some programmer dude

You don't use the dollar sight when creating variables, only when accessing them.

创建变量时不使用美元视线,仅在访问它们时使用。

So change

所以改变

$elf=" main.elf"
$c=" $main.c"
$gcc="avr-gcc -mmcu=atmega128 -Wall -Os -o $elf$c"

to

elf=" main.elf"
c=" $main.c"
gcc="avr-gcc -mmcu=atmega128 -Wall -Os -o $elf$c"