MTT
MTT

Reputation: 5263

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

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

./executable file input.txt parameter output.txt

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

#!/bin/bash
file_name=$(echo $1|sed 's/\(.*\)\.cpp/\1/')
g++ -o $file_name.out $1
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.

Upvotes: 0

Views: 8054

Answers (1)

TheDuke
TheDuke

Reputation: 760

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

#!/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

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

% 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

Upvotes: 2

Related Questions