0

How can I write a .sh file to automate input? For example I have a simple program that asks for a name and a few other things. I have so far

#!/bin/bash

echo alice
echo 5

I try to use it like ./program < ./file.sh, but it seems to take #!/bin/bash as input. I am wanting the first input the program takes to be alice and then directly after 5 which should terminate the program

2 Answers 2

2

why are you using file.sh as input stream ? just create a simple plain text file and keep each value on separate row

myscript.sh

#!/bin/bash

read "Enter your name : " a
read "Enter your age : " b  

echo $a 
echo $b

input.txt

Kashan
21

output

~$ ./myscript < input.txt

kashan
21


 
Sign up to request clarification or add additional context in comments.

2 Comments

If the data to be sent to the program is not simple text as shown in the question but needs some calculation or processing in the script, it could be used as ./file.sh | ./program
@KashanBaig I going to have to do it for quite a few programs so I thought it would be easiest. I started thinking if its possible to run a program from a .sh file? I have a .sh with the following content /ctf/myprogram echo hello this seems to open and run the program, but doesnt pass the hello as input to the first prompt directly after. Is there an alternate way that might just use a .txt file to do this?
0

You can use the command redirection syntax:

./program < <(./file.sh)

Basically, it first executes the script file.sh then it puts the output it gets in a temporary file, then the temporary file is passed as stdin to the first program with usual file-redirection syntax.

The problem with your incantation is that the bash syntax you are using is for file redirection, where the contents of the file are being passed as input to the first program. What you want to do is pass the output of the file.sh script instead of the actual text in it.

1 Comment

The order of operations described in this answer is incorrect -- both ./file.sh and ./program are running at the same time. The "temporary file" is a named pipe, not a regular file, so it connects the components in real time. If you want ./file.sh to run first and to only start ./program after it finishes, then you would use ./program <<<"$(./file.sh)" instead.

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.