Filipi Silva
Filipi Silva

Reputation: 147

How does one suppress the output of a command?

I would like to run some commands in my shell script however would like to know some method to it returns nothing.

example:

#! / bin / bash]
rm / home / user

return: rm: can not lstat `/ home / user ': No such file or directory

I would have put the command to run invisibly no return!

Upvotes: 0

Views: 1795

Answers (2)

Reinstate Monica Please
Reinstate Monica Please

Reputation: 11653

Your direct error is coming from incorrect spacing in the path, should be rm /home/whatever without spaces in the path, assuming you don't have actual spaces in the dir names (in which case you will need to quote or escape properly)

About suppressing output. Redirecting stdout here is a bit strange.

$ touch test.txt
$ rm test.txt > /dev/null 2>&1

^ interactive rm is actually asking if you really want to delete the file here, but not printing the message

If you just want to not get error messages, just redirect stderr (file descriptor 2) to /dev/null

$ rm test.txt 2> /dev/null

or

$ rm test.txt 2>&-

If you want it to not prompt do you really want to delete type messages, use the force flag -f

$ rm -f test.txt 2> /dev/null

or

$ rm -f test.txt 2>&-

To delete a directory you either want rmdir if it's empty or use the recursive -r flag, however, this will wipe away everything /home/user so you really need to be careful here.

Unless you have it running in --verbose mode, I can't think of any case where it needs to close stdout for the rm command.

Also as of bash 4, if you want to redirect both stdout and stderr to the same location just use rm whatever &> /dev/null or something similar

Upvotes: 1

DopeGhoti
DopeGhoti

Reputation: 767

To suppress the standard output of a command, the conventional way is to send the output to the null device, with somecommand arg1 arg2 > /dev/null. To also suppress error output, standard error can be redirected to the same place: somecommand arg1 arg1 > /dev/null 2>&1.

Upvotes: 4

Related Questions