2013-03-21 24 views
0

我有一個C++程序和命令在Linux終端運行是:我應該如何創建一個bash腳本來運行C++程序?

./executable file input.txt parameter output.txt 

我想打一個bash腳本它,但我不能。我試過這一個:

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

但它是不正確的,因爲它沒有得到輸入和數值參數。提前致謝。

回答

2

此腳本假定第一個參數是源文件名,並且它是一個.cpp文件。錯誤處理髮射簡潔。

#!/bin/bash 
#set -x 
CC=g++ 
CFLAGS=-O 
input_file=$1 
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 

因此,例如運行腳本「DOIT」的論據「myprogram.cpp input.txt的參數output.txt的」,我們看到:

% 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 
+0

,並在你的腳本的一部分,我應該修改我的exe文件,輸入和數值參數?對不起,我是bash腳本編程的初學者。 – MTT 2013-03-21 22:46:12

+0

如果我正確理解了您的用例,則不需要修改腳本 - 它應該按原樣運行。還是你有其他的期望?如果是這樣,請修改您的問題,更準確地說明您希望腳本執行什麼操作。 – TheDuke 2013-03-22 00:32:55

+0

非常感謝。唯一的是,因爲我有一個makefile,那麼我有一個exe文件,而不是cpp。這意味着我在終端中運行代碼的命令是:./myprogram.exe input.txt參數output.txt。 – MTT 2013-03-22 02:03:26

相關問題