Background reading: Why does my shell script choke on whitespace or other special characters?, Why you shouldn't parse the output of ls
IFS to a newline means that only newlines, and not spaces and tabs, will be treated as separators during the expansion of the command substitution. Your method will not support file names that contain newlines; this is a fundamental limitation of
Furthermore, and this is what you ran against, setting
IFS has no effect on the other thing that happens on the expansion of a command substitution, which is globbing (wildcard matching). You can turn off globbing, and then your script will work as long as file names don't contain newlines.
set -- *"$IFS"*
if [ -e "$1" ]; then
echo >&2 "There are file names with newlines. I cannot cope with this."
for i in $(ls -1Atu); do
printf '%s\n' "$i"
The easy, reliable way to enumerate files by date is to use something other than a pure Bourne-style shell, such as zsh which has glob qualifiers to modify the way wildcard matches are sorted.
¹ You can work around it with some
ls implementations, but not if you need portability.