faho
changed the title
Try input redirection
<? try-input redirection
This tries to open the given file to use as stdin, and if it fails, for any reason, it uses /dev/null instead. This is useful in cases where we would otherwise do either of these: ```fish test -r /path/to/file and string match foo < /path/to/file cat /path/to/file 2>/dev/null | string match foo ``` This both makes it nicer and shorter, *and* helps with TOCTTOU - what if the file is removed/changed after the check? The reason for reading /dev/null instead of a closed fd is that a closed fd will often cause an error. In case opening /dev/null fails, it still skips the command. That's really a last resort for when the operating system has turned out to be a platypus and not a unix. Fixes fish-shell#4865
This is mostly used instead of `test -r foo && string match bar <foo` or `set bar (cat foo 2>/dev/null)`. In doing so it can avoid a weird race condition where the file changes between the check and the use, and it can avoid an external process or having to open the file twice. However it can also cause more work to happen - if you do ```fish if test -r file # do a lot of work with file end ``` it might be prudent to keep doing that. In the cases here it's usually just a few `string` calls, which would operate on nothing and so be pretty quick.
faho deleted the try-input-redirection branch
May 7, 2024 06:50
github-actions
Bot
locked as resolved and limited conversation to collaborators