help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Suppress a "No such file” message when using the ls command


From: Greg Wooledge
Subject: Re: Suppress a "No such file” message when using the ls command
Date: Mon, 30 Mar 2020 13:44:13 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Mon, Mar 30, 2020 at 07:28:09PM +0200, Richard Taubo wrote:
> This works in zsh:
> my_last_file=$(/bin/ls -t *.pdf  | head -1) 2> /dev/null

I seriously, strongly, massively doubt that this works in zsh, or in any
shell.  The issue isn't the shell, after all -- it's ls.  ls does not
handle filenames with newlines in anything resembling a sane manner.

On the other hand, recent versions of GNU coreutils have a version of
ls that has options to produce shell-parseable filename encodings.  Because
just giving us a --null option would have been too good, and we're not
allowed to have anything good.  (No, seriously, that was their rationale.)

If you have GNU coreutils ls, and it's recent enough, you can use this
recipe (from <https://mywiki.wooledge.org/ParsingLs>):

eval "sorted=( $(ls -t --quoting-style=shell-escape *.pdf) )"
printf 'The newest file is <%s>.\n' "${sorted[0]}"

Now, you also appear to have been confused about where the 2>/dev/null
goes.  The obvious solution is to turn on nullglob, and then you don't
need the 2>/dev/null at all.

shopt -s nullglob
eval "sorted=( $(ls -t --quoting-style=shell-escape *.pdf) )"
if ((! ${#sorted[@]})); then
  echo "No matching files."
  exit
fi
printf 'The newest file is <%s>.\n' "${sorted[0]}"

But if you insist on not using nullglob in this script, the 2>/dev/null
goes on the ls command.  Not on the assignment, or anywhere else.

eval "sorted=( $(ls -t --quoting-style=shell-escape *.pdf 2>/dev/null) )"
if ((! ${#sorted[@]})); then
  echo "No matching files."
  exit
fi
printf 'The newest file is <%s>.\n' "${sorted[0]}"



reply via email to

[Prev in Thread] Current Thread [Next in Thread]