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

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`" 

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.


You can use one of:

./program $(cat file)
./program "$(cat file)"

The latter is useful if there may be multiple words in the file and you want them to be treated as a single argument. In any case, I prefer the use if $() to backticks simply due to it's ability to nest (which is probably not a requirement in this case).

Also keep in mind that this answer (and others) are more related to the shell in use rather than Linux itself. Since the predominant and the best :-) shell seems to be bash, I've coded specifically for that.

This is actually a fairly common way of killing processes under UNIX lookalikes. A daemon (like cron) will write its process ID to a file (like /var/cron.pid) and you can signal it with something like:

kill -HUP $(cat /var/cron.pid)

Tags:

Linux