0

I am new to scripting. Facing a problem in trying to do the following. Please help.

My C++ program runs in a while loop, receives commands from the user on a prompt, and executes them. I want to automate this process.

Sample execution

$ ./my_tool

my_prompt> command1 arg1 arg2

result: abc

my_prompt> command2 arg3

result: xyz

my_prompt> command3 abc xyz

result: my_result

my_prompt> exit

$

Now, I want to have a file, input.txt, which will have

command1 arg1 arg2
command2 arg3
command3 <abc> <xyz>
exit

Execution of the script will be something like

./run ./my_tool input.txt

How do I write a simple bash script to achieve this? I will have at least 20 commands.

If I don't have command3, that is, all input parameters are predetermined, then how can I proceed?

Sorry if this is really simple - I am not able to figure out.

Thanks and regards, SB

1 Answer 1

1

You can pass the file line by line to the binary as stdin:

#!/bin/bash

while IFS='' read -r line || [[ -n "$line" ]]; do
    eval $1 < $line
done <<< "$2"

Quick explanation: The IFS thing will make sure the file will be read line by line, otherwise it would create a new iteration on each whitespace. The line ./my_tool < $line will pass $line as stdin to your program so the stdin buffer (where you would read user input from) is filled with the data, so your program reads the "input". done < "$2" will pass the first argument as file to the while loops input, where read will read the input. $2 will be the filename you pass the script upon execution. eval $1 will run the command that is stored in $1 which is your first parameter of the script.

To use it run:

chmod +x myscript.sh # you need to do this only once
./myscript.sh ./my_tool input.txt
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I am getting $line: ambiguous redirect for each line of the input file and exit: No such file or directory on the last line for exit. Am I doing something wrong?
Changing the last line to done <<< "$2" is working for me. Is that a proper thing to do here?
Thank you. This is exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.