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: Richard Taubo
Subject: Re: Suppress a "No such file” message when using the ls command
Date: Mon, 30 Mar 2020 20:22:11 +0200


> On 30 Mar 2020, at 19:44, Greg Wooledge <address@hidden> wrote:
> 
> 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.)

Really!?!

In my case I know what the files will look like, so no newlines etc.
Think I would have used ‘find’ with -print0 if that had not been the case.

> 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.
Yes :-) But it somehow got suppressed in zsh. :-)
Like I said, was thinking about going with the following in bash as that worked:
my_last_file=$(/bin/ls -t *.pdf  2> /dev/null)

> 
> 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]}"

Thanks for the information! :-)

Richard Taubo


reply via email to

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