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
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.
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.
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`"
./program "$(< file)"
$(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.
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)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With