You'll be wanting to use the 'read' command
while read name
do
echo "$name"
done < names.txt
Note that "$name" is quoted -- if it's not, it will be split using the characters in $IFS
as delimiters. This probably won't be noticed if you're just echoing the variable, but if your file contains a list of file names which you want to copy, those will get broken down by $IFS
if the variable is unquoted, which is not what you want or expect.
If you want to use Mike Clark's approach (loading into a variable rather than using read), you can do it without the use of cat
:
NAMES="$(< scripts/names.txt)" #names from names.txt file
for NAME in $NAMES; do
echo "$NAME"
done
The problem with this is that it loads the whole file into $NAMES
, when you read it back out, you can either get the whole file (if quoted) or the file broken down by $IFS
, if not quoted. By default, this will give you individual words, not individual lines. So if the name "Mary Jane" appeared on a line, you would get "Mary" and "Jane" as two separate names. Using read
will get around this... although you could also change the value of $IFS