How to write a shell script(any shell languages) that interacts with a program and passes arguments?

77 views Asked by At
#include <iostream>
using namespace std;

int main(void){
  int number = 0;
  cout << "Please enter a number: ";
  cin >> number ;
  cout << "the number you enter is " << number << endl;

  return 0;}

This is my program that takes in an argument and prints it out.

#! /bin/bash
number=1
echo "1" | ./a.out #>> result.txt

This is my bash script that is trying to pass an argument to the program.

1
Please enter a number: the number you enter is 1

This is the result.txt. I wanted it more like this:

Please enter a number: 1
the number you enter is 1

How should I fix it so that the script would pass the argument more like a human does.

And is bash a really good scripting language doing this kind of work or there are other better scripting languages. (google says tcl is better that bash for this kind of interactive program?)

1

There are 1 answers

1
Cole Tierney On

Unless I'm misunderstanding the problem, if you'd like to pass parameters to your c++ program, you should add argc and argv to your main function.

Your program.cpp:

#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
    cout << "your number is " << argv[1] << endl;
    return 0;
}

The shell script (send-arg.sh):

#!/bin/sh

./program 42

Output:

./send-arg.sh
your number is 42