Search code examples
evalfile-descriptorio-redirectionfish

Pipe the output of eval/source in fish shell


I want to pipe the output of eval to a file. That works as expected if the command execution is successful:

eval ls > log.txt 2>&1
cat log.txt # Documents Desktop

It also works if the command is not successful

eval rm Desktop > log.txt 2>&1
cat log.txt # rm: cannot remove 'Desktop': Is a directory

However, I do not manage to redirect stderr if the command does not exist

eval abcde > log.txt 2>&1 # fish: Unknown command abcde
cat log.txt # (empty)

How can I redirect also the output of the third case to a log file?


Something that works with source would also be very much appreciated:

echo abcde | source > log.txt 2>&1

Solution

  • However, I do not manage to redirect stderr if the command does not exist

    That's because the output is not coming from eval or the command, it's coming from your command-not-found handler.

    Try checking if the command exists before you try to execute it. If you absolutely can't, it's technically possible to silence the command-not-found error entirely by redefining __fish_command_not_found_handler:

    function __fish_command_not_found_handler; end
    

    You'd have to handle moving it back afterwards via functions --copy:

    functions --copy __fish_command_not_found_handler oldcnf
    

    Overall I don't recommend any of this and suspect you might be overusing eval.

    Something that works with source would also be very much appreciated:

    That's what eval is for, quite literally. Up to the upcoming 3.1 release eval is a function that's just source with some support code that mostly boils down to handling these redirections.