I have a file file1
with the following contents:
Z
X
Y
I can use cat
to view the file:
$ cat file1
Z
X
Y
I can sort the file:
$ sort -k1,1 file1
X
Y
Z
I can sort it and store the output in a variable:
sorted_file1=$(sort -k1,1 file1)
But when I try to use cat
on the variable sorted_file1
I get an error:
$ cat "$sorted_file1"
cat: X
Y
Z: No such file or directory
I can use echo
and it looks about right, but it behaves strangely in my scripts:
$ echo "$sorted_file1"
X
Y
Z
Why does this happen? How does storing the output of a command change how cat interprets it?
Is there a better way to store the output of shell commands within variables to avoid issues like this?