I have a text file named links.txt which looks like thislink1link2link3I want to loop through this file line by line and perform an operation on every line. I know I can do this using while loop but since I am learning, I thought to use a for loop.I actually used command substitution like this a=$(cat links.txt)Then used the loop like thisfor i in $a; do ###something###;doneAlso I can do something like thisfor i in $(cat links.txt); do ###something###; doneNow my question is when I substituted the cat command output in a variable a, the new line characters between link1 link2 and link3 are removed and is replaced by spacesecho $aoutputslink1 link2 link3and then I used the for loop.Is it always that a new line is replaced by space when we do a command substitution??Regards
Why do newline characters get lost when using command substitution?
shell;newlines;command substitution
The newlines were lost, because the shell had performed field splitting after command substitution.In POSIX Command Substitution section:The shell shall expand the command substitution by executing command  in a subshell environment (see Shell Execution Environment) and  replacing the command substitution (the text of command plus the  enclosing $() or backquotes) with the standard output of the  command, removing sequences of one or more  characters at the  end of the substitution. Embedded  characters before the end  of the output shall not be removed; however, they may be treated as  field delimiters and eliminated during field splitting, depending on  the value of IFS and quoting that is in effect. If the output contains  any null bytes, the behavior is unspecified.Default IFS value (at least in bash):$ printf '%q\n' $IFS$' \t\n'In your case, you don't set IFS or using double quotes, so newlines character will be eliminated during field splitting.You can preserve newlines, example by settingIFSto empty:$ IFS=$ a=$(cat links.txt)$ echo $alink1link2link3