Why is my echo command showing an error message?

0
3
Asked By CloudyFox23 On

I'm running a command in bash on Fedora 41 using GNOME terminal, and I expect it to print nothing. However, when I run `echo $(ls /sdfsdgd) &> /dev/null`, it still outputs an error message from the `ls` command. Can someone explain why this happens? I'm a bit confused and can't seem to figure it out. Thanks!

4 Answers

Answered By TechGuru42 On

You're encountering this because `$(...)` only captures `stdout`, not `stderr`. So when you run `ls` and it fails, that error message is still printed to the terminal. Try changing your command to `echo $(ls /sdfsdgd 2>/dev/null)` to suppress the error from being printed.

Answered By SystemWhisperer37 On

An important point is that when using `$()`, it evaluates the command before your redirection. So, standard errors from `ls` are still reaching the terminal. If you want to combine `stdout` and `stderr`, use `&> /dev/null` with `ls` directly: `ls /sdfsdgd &> /dev/null` before passing it to `echo` for a clean output.

Answered By CuriousCoder99 On

The issue is that while you redirect the output of `echo`, the error messages from the `ls` command inside the subshell are still sent to the terminal. To stop the error from showing up, you need to redirect the `stderr` from `ls` as well. For instance, you could use `2> /dev/null` in the command: `echo $(ls /sdfsdgd 2>/dev/null)`. This way, both the standard output and standard errors are taken care of!

CloudyFox23 -

Thanks, I just figured that out myself. I am marking it as solved.

Answered By BashNinja88 On

Just redirecting `stdout` to `/dev/null` is not enough. You need to specifically redirect the `stderr` too. You can achieve this using `2>&1` to link it. For your case, using something like `echo $(ls /sdfsdgd 2>&1) > /dev/null` will ensure no error messages hit your terminal.

CloudyFox23 -

No, &> means both 2>&1 afaik. The problem is as others have already pointed out.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.