linux - 用于编译和运行 C++ 程序的 Bash 脚本
问题描述
我正在编写一个 bash 脚本来编译和运行 C++ 程序。这是我的脚本
#!/bin/bash
PROG_NAME=$1
output=$(g++ $PROG_NAME) #redirect the error to a variable
echo $output #show the error on stdout
if [$output = ""]
then
./a.out
fi
a.out
如果程序无法编译,我不想运行该文件。为此,我创建了一个变量来存储编译时错误消息。但是这种方法似乎不起作用,因为输出没有被重定向到变量。还有其他方法吗?
编辑
这是对我有用的脚本
#!/bin/bash
PROG_NAME=$1
g++ -Werror $PROG_NAME
if [[ $? == 0 ]]; then
./a.out
fi
解决方案
如果g++
失败,它将返回一个非零返回值,可以使用 Bashif
命令检查:
output=$(g++ $PROG_NAME 2>&1)
if [[ $? != 0 ]]; then
# There was an error, display the error in $output
echo -e "Error:\n$output"
else
# Compilation successfull
./a.out
fi
一个可能更好的解决方案 (IMO) 是学习如何使用 makefile,因为它也将允许更复杂的项目。
推荐阅读
- java - 按数字键盘实现游戏结果输入
- php - ORA-01747 错误,使用输入更新数据库
- java - 将响应标头解析为自定义 POJO
- ionic4 - 在 Ionic 4 (Newsapi) 上点击不同新闻的相同新闻细节
- excel-2016 - 如何在管理规则中选择多个条件格式规则?
- amazon-web-services - AWS Data Pipeline 与 Step Functions
- python - NotImplementedError:重载函数“new_RoutingModel”的参数数量或类型错误
- html - WebM Alpha 仅显示在 Chrome 中?
- c# - 如何使用 C# 在图片框中添加标注?
- java - Java 堆栈跟踪中的斜线是什么意思?