我应该如何制作 bash 脚本来运行 C++ 程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15557585/
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-09-18 04:56:44  来源:igfitidea点击:

How I should make a bash script to run a C++ program?

bash

提问by MTT

I have a C++ program and its command to run in linux terminal is:

我有一个 C++ 程序,它在 linux 终端中运行的命令是:

./executable file input.txt parameter output.txt

I want to make a bash script for it, but I cannot. I tried this one:

我想为它制作一个 bash 脚本,但我不能。我试过这个:

#!/bin/bash
file_name=$(echo |sed 's/\(.*\)\.cpp//')
g++ -o $file_name.out 
if [[ $? -eq 0 ]]; then
    ./$file_name.out
fi

but it is not right, because it does not get input and also numerical parameter. Thanks in advance.

但这是不对的,因为它没有得到输入和数字参数。提前致谢。

回答by TheDuke

This script assumes the first argument is the source file name and that it's a .cpp file. Error handling emitted for brevity.

此脚本假定第一个参数是源文件名,并且它是一个 .cpp 文件。为简洁起见发出错误处理。

#!/bin/bash
#set -x
CC=g++
CFLAGS=-O
input_file=
shift # pull off first arg
args="$*"
filename=${input_file%%.cpp}

$CC -o $filename.out $CFLAGS $input_file
rc=$?

if [[ $rc -eq 0 ]]; then
   ./$filename.out $args
   exit $?
fi

exit $rc

So, for example running the script "doit" with the arguments "myprogram.cpp input.txt parameter output.txt" we see:

因此,例如运行带有参数“myprogram.cpp input.txt parameter output.txt”的脚本“doit”,我们看到:

% bash -x ./doit myprogram.cpp input.txt parameter output.txt
+ set -x
+ CC=g++
+ CFLAGS=-O
+ input_file=myprogram.cpp
+ shift
+ args='input.txt parameter output.txt'
+ filename=myprogram
+ g++ -o myprogram.out -O myprogram.cpp
+ rc=0
+ [[ 0 -eq 0 ]]
+ ./myprogram.out input.txt parameter output.txt
+ exit 0