Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using linux how can I pass the contents of a file as a parameter to an executable?

Tags:

linux

let's say I want to run ./program with a string argument

instead of typing ./program string each time, how can I do ./program <file> where <file> is a file that contains string?

thankyou

like image 522
al b. Avatar asked Nov 22 '10 00:11

al b.


People also ask

How do you read the contents of a file in Linux?

Cat. The simplest way to view text files in Linux is the cat command. It displays the complete contents in the command line without using inputs to scroll through it. Here is an example of using the cat command to view the Linux version by displaying the contents of the /proc/version file.

How do you display the contents of a file in shell script?

You can also use the cat command to display the contents of one or more files on your screen. Combining the cat command with the pg command allows you to read the contents of a file one full screen at a time. You can also display the contents of files by using input and output redirection.


2 Answers

This should do the trick:

./program `cat file` 

If you want the entire file content in a single argument, add double quotation (tested in bash. I think It may vary shell to shell) :

./program "`cat file`"  
like image 103
robbrit Avatar answered Oct 10 '22 09:10

robbrit


Command

./program "$(< file)" 

Explanation

  1. $(cmd) runs a command and converts its output into a string. $(cmd) can also be written with backticks as `cmd`. I prefer the newer $(cmd) as it nests better than the old school backticks.

  2. The command we want is cat file. And then from the bash man page:

    The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

  3. The quotes around it make sure that whitespace is preserved, just in case you have spaces or newlines inside of your file. Properly quoting things in shell scripts is a skill that is sorely lacking. Quoting variables and command substitutions is a good habit to good into so you don't get bit later when your file names or variable values have spaces or control characters or other weirdnesses.

like image 37
John Kugelman Avatar answered Oct 10 '22 11:10

John Kugelman