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
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
Command
Explanation
$(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 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.
Another option is xargs:
I personally find this version easier to read, especially if you're doing more than just catting a file.
From the man page:
In plain speak, xargs will execute ./program on each line/word that is being piped to it.
See man xargs for more options.
This should do the trick:
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) :
This is extension to @robbrit answer.
Consider a file.txt with content:
And the a program.c with content:
Here is what happen if you pass command line arguments with quotes and without:
All the above answers work but I find the cleanest and easiest to type option is
You can use one of:
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: