While in a Linux shell I have a string which has the following contents:
cat
dog
bird
and I want to pass each item as an argument to another function. How can I do this?
While in a Linux shell I have a string which has the following contents:
cat
dog
bird
and I want to pass each item as an argument to another function. How can I do this?
Just pass your string to your function:
gives you:
And if you really care about other whitespaces being taken as argument separators, first set your
IFS
:to get:
Do not forget to
unset IFS
after that.if you use bash, setting IFS is all you need:
Use
read
with a while loop:Use this (it is loop of reading each line from file
file
)where the
echo $a
is whatever you want to do with current line.UPDATE: from commentators (thanks!)
If you have no file with multiple lines, but have a variable with multiple lines, use
UPDATE2: "
read -r
" is recommended to disable backslashed (\
) chars interpretation (check mtraceur comments; supported in most shells). It is documented in POSIX 1003.1-2008 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.htmlDo like this:
Variable $mulstrs must be enclosed in double quotes, otherwise spaces or carriage returns will interfere with the calculation.
Use
xargs
:Depending on what you want to do with each line, it could be as simple as:
or more complicated using: