Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
871 views
in Technique[技术] by (71.8m points)

bash - UNIX: How to run a program with a file as an input

I'm writing a bash script called 'run' that tests programs with pre-defined inputs.

It takes in a file as the first parameter, then a program as a second parameter.

The call would look like

./run text.txt ./check

for example, the program 'run' would run 'check' with text.txt as the input. This will save me lots of testing time with my programs.

right now I have

$2 < text.txt > text.created

So it takes the text.txt and redirects it as input in to the program specified, which is the second argument. Then dumps the result in text.created.

I have the input in text.txt and I know what the output should look like, but when I cat text.created, it's empty.

Does anybody know the proper way to run a program with a file as the input? This seems intuitive to me, but could there be something wrong with the 'check' program rather than what I'm doing in the 'run' script?

Thanks! Any help is always appreciated!

EDIT: the file text.txt contains multiple lines of files that each have an input for the program 'check'.

That is, text.txt could contain

asdf1.txt asdf2.txt asdf3.txt

I want to test check with each file asdf1.txt, asdf2.txt, asdf3.txt.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The < operator redirects the contents of the file to the standard input of the program. This is not the same as using the file's contents for the arguments of the file--which seems to be what you want. For that do

./program $(cat file.txt) 

in bash (or in plain old /bin/sh, use

./program `cat file.txt`

).

This won't manage multiple lines as separate invocations, which your edit indicates is desired. For that you probably going to what some kind scripting language (perl, awk, python...) which makes parsing a file linewise easy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...