Score:2

Why does "less" accept an empty filename, and show some environment variables?

cn flag

I ran a less command that I expected to fail because the filename would be empty, but to my surprise, it printed some environment variables:

$ less -XE "$(which nonexistent-script)"
export LESSOPEN="| /usr/bin/lesspipe %s";
export LESSCLOSE="/usr/bin/lesspipe %s %s";

(-XE basically makes it behave like cat.)

cat, on the other hand, fails:

$ cat "$(which nonexistent-script)"
cat: '': No such file or directory

Why does less do this? I can only imagine it being problematic, because if there's some bug in your code that causes an empty filename, you'll get bogus output.

While we're here, why does it print those environment variables? Are they from my environment? They're identical:

$ declare -p LESSOPEN LESSCLOSE 
declare -x LESSOPEN="| /usr/bin/lesspipe %s"
declare -x LESSCLOSE="/usr/bin/lesspipe %s %s"

I checked man less but the filename parameter doesn't seem to be documented explicitly. Other mentions of it didn't seem to be related to this behaviour. I also checked the less FAQ.

hr flag
It looks like executing `lesspipe` with an empty filename is a special usage, intended to be done from a shell setup script in order to set the environment for subsequent `less` invocations. See for example [Can you explain eval expression in the default .bashrc](https://askubuntu.com/questions/724351/can-you-explain-eval-expression-in-the-default-bashrc). I don't know where this is documented.
wjandrea avatar
cn flag
@steeldriver Huh, you're right! I just tried `less --no-lessopen ''` and it failed with `: No such file or directory`. So if I'm understanding correctly, this is a quirk of the Ubuntu setup? (and maybe the upstream Debian setup too?)
user10489 avatar
in flag
Well, it's a quirk of lesspipe at least, and the lesspipe man page says it was written for Debian.
wjandrea avatar
cn flag
@steeldriver It looks like the root problem is that `less` doesn't properly quote the string it's passing to `LESSOPEN`, instead all it does is ["Insert a backslash before each metacharacter"](https://github.com/gwsw/less/blob/1d0e8245cd32b149101039adfc0a379daf778de1/filename.c#L138-L143). I'd rather it didn't try to quote it at all, then we would quote the filename in the config: `LESSOPEN='| /usr/bin/lesspipe "%s"'`.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.