Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 直接运行命令与从环境变量运行命令_Bash_Command Line_Environment Variables - Fatal编程技术网

Bash 直接运行命令与从环境变量运行命令

Bash 直接运行命令与从环境变量运行命令,bash,command-line,environment-variables,Bash,Command Line,Environment Variables,我试图用g++编译和执行一个程序,然后我得到了命令: g++ -o example example.cpp && ./example 它运行正常。我试图设置一个环境变量以节省时间: COMPRUN="g++ -o example example.cpp && ./example" (echo$COMPRUN告诉我任务没有问题)。但是当我尝试使用$COMPRUN执行它时,我得到了g++:error:&&:没有这样的文件或目录 别名可以正常工作(所以我原来的问题解

我试图用g++编译和执行一个程序,然后我得到了命令:

g++ -o example example.cpp && ./example
它运行正常。我试图设置一个环境变量以节省时间:

COMPRUN="g++ -o example example.cpp && ./example"
(echo$COMPRUN告诉我任务没有问题)。但是当我尝试使用
$COMPRUN
执行它时,我得到了
g++:error:&&:没有这样的文件或目录

别名可以正常工作(所以我原来的问题解决了),但环境变量不行


为什么运行命令与从环境变量运行命令直接不同?命令行是如何解释我的命令以得到“没有这样的文件”错误的?

您得到错误的原因是shell没有解释命令行。因此,
&&
被视为简单字符串(命令上下文中的文件名),而不是被解释为控制运算符。您必须使用
eval$COMPRUN
让shell实际计算命令字符串。

使用shell函数而不是变量来封装任意代码

$ comprun () {
    g++ -o "$1" "$1".cpp && ./"$1"
}
$ comprun example
参数扩展发生在命令行已被解析之后,因此无法识别任何语法结构(如
&&
)。在您的情况下,不存在的文件是“&&”