Reading a file causes directory list output
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
Ubuntu |
Invalid
|
Undecided
|
Unassigned |
Bug Description
Reading a file line by line gives unexpected result if a file contains */ or /*
File test.sh
-------------- begin
#!/bin/bash
while IFS='' read -r line; do
echo $line
done < $1
-------------- end
File test1.sh
-------------- begin
Ubuntu 1
Ubuntu /
Ubuntu 2
-------------- end
Command ./test.sh test1.txt outputs correct lines
Ubuntu 1
Ubuntu /
Ubuntu 2
File test2.sh
-------------- begin
Ubuntu 1
Ubuntu /*
Ubuntu 2
-------------- end
Command ./test.sh test2.txt outputs the list of the root folder!!! in addition to lines in the file test2.txt
Ubuntu 1
Ubuntu /bin /boot /dev /etc /home /initrd.img /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /snap /srv /sys /tmp /usr /var /vmlinuz
Ubuntu 2
Each occurrence of /* adds the list of the root directory
Each extra /* adds one level of directories in the list of the root directory, so eventually you can get the whole folder structure.
The combination */ causes output of the list of folders in the directory where is the script is running from.
I am running the fresh installation
root@mxa:/etc/mail# uname -a
Linux mxa 4.4.0-62-generic #83-Ubuntu SMP Wed Jan 18 14:10:15 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
The bug is in your code. Instead of:
echo $line
... you must write:
echo "$line"
Lacking the double quotes here means that the result of expanding $line then undergoes pathname expansion, which you don't want in this case.
In general you should always ensure that any $-expansion in a shell script is surrounded by double quotes unless you have a specific reason not to do so.