How do I use the lines of a file as arguments of a command?
command `< file`
will pass file contents to the command on stdin, but will strip newlines, meaning you couldn't iterate over each line individually. For that you could write a script with a 'for' loop:
for line in `cat input_file`; do some_command "$line"; done
Or (the multi-line variant):
for line in `cat input_file`
do
some_command "$line"
done
Or (multi-line variant with $()
instead of ``
):
for line in $(cat input_file)
do
some_command "$line"
done
References:
- For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/
As already mentioned, you can use the backticks or $(cat filename)
.
What was not mentioned, and I think is important to note, is that you must remember that the shell will break apart the contents of that file according to whitespace, giving each "word" it finds to your command as an argument. And while you may be able to enclose a command-line argument in quotes so that it can contain whitespace, escape sequences, etc., reading from the file will not do the same thing. For example, if your file contains:
a "b c" d
the arguments you will get are:
a
"b
c"
d
If you want to pull each line as an argument, use the while/read/do construct:
while read i ; do command_name $i ; done < filename
You do that using backticks:
echo World > file.txt
echo Hello `cat file.txt`
If your shell is bash (amongst others), a shortcut for $(cat afile)
is $(< afile)
, so you'd write:
mycommand "$(< file.txt)"
Documented in the bash man page in the 'Command Substitution' section.
Alterately, have your command read from stdin, so: mycommand < file.txt