Linux redirect all to stdout

BASH Shell Redirect Output and Errors To /dev/null

H ow do I redirect output and errors to /dev/null under bash / sh shell scripting? How do I redirect the output of stderr to stdout, and then redirect this combined output to /dev/null device? In Unix, how do I redirect error messages to /dev/null?

You can send output to /dev/null, by using command >/dev/null syntax. However, this will not work when command will use the standard error (FD # 2).

Tutorial details
Difficulty level Easy
Root privileges No
Requirements bash/ksh
Est. reading time 1m

So you need to modify >/dev/null as follows to redirect both output and errors to /dev/null.

Syntax to redirect error and output messages to /dev/null

The syntax discussed below works with Bourne-like shells, such as sh, ksh, and bash:

You can also use the same syntax for all your cronjobs to avoid emails and output / error messages:
@hourly /scripts/backup/nas.backup >/dev/null 2>&1
OR
@hourly /scripts/backup/nas.backup &>/dev/null

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Redirect both standard error and standard out messages to a log file

You can always redirect both standard error (stdin) and standard out (stdout) text to an output file or a log file by typing the following command:

Want to close stdout and stderr for the command being executed on a Linux/Unix/BSD/OSX bash shell?

Try the following syntax:

See man pages: ksh(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Another way to do it:

Or you can close stdout and stderr for the command being executed:

Remember to add an additional & at the end of the statement to run the command in the background. Thank you Giuseppe for the tip.

What do you mean by “close stdout and stderr” ?

Thanks! I was searching how resolve this problem, and your solution work perfect for me!

need a command in my bash script to remove some (not all) of the contents of directory2.
The script does NOT run as root, which works because it removes the correct files but not the root-level stuff in directory2 (that I don’t want to remove).
Problem is users get confused by the “permission denied” msgs output by the “rm”. So…
I tried to redirect the stderror & stdout to /dev/null this way:
rm * /directory1/directory2/ > 2&>1 /dev/null
kept changing /dev/null form a special file & other users need crw-rw-rw-
Will the recommended approaches allow me to redirect to /dev/null without messing it up for others?

You could use find instead to filter out the files you don’t want to delete, or only delete files matching a patter:

Delete all files except those with “attachments” in the name:
# find . ! -name ‘*attachments*’ -exec rm -v <> \;

Delete all files with “attachments” in the name:
# find . -name ‘*attachments*’ -exec rm -v <> \;

Find is very versitile, it’s pretty cool what you can acheive with find.

how does one redirect output from text file processing to a script file that uses the command line variable $1.

file iplist has a long list of IP’s on the network and i need to send this to a script that creates a file with the ping info.

script says: ping $1 > $1
Please assist if possible

How reliable, if that’s the word I’m looking for, is ending a particular command in a script with a redirect like “2>/dev/null” ? What have folks’ experiences been with the different commands and bash/sh versions when trying it this way?

I know it’s not recommended, but for someone like myself, with scripts they either run daily or don’t run for months and then go through a spate of executing them two and three times a day (only to go back to seldom running them until the next time it happens), it would be very convenient and not too too anxiety-producing to run a script and know that whatever passable or critical errors it comes up with are being suppressed.

I’m much more inclined to put up with circumstances after the fact, and I seldom write anything that’s too destructive (on the system or OS/hardware install and performance level, at any rate) for a little error like Exiv2 complaining about some JPG file’s Photoshop IFD entry being out of bounds.

Источник

BASH Shell Redirect stderr To stdout ( redirect stderr to a File )

Table of contents

Understanding I/O streams numbers

The Unix / Linux standard I/O streams with numbers:

Tutorial requirements
Requirements Unix or Linux with bash
Root privileges No
Difficulty Easy
Est. reading time 6 mintues
Handle Name Description
0 stdin Standard input
1 stdout Standard output
2 stderr Standard error

Redirecting output

Redirecting the standard error stream to a file

The following will redirect program error message to a file called error.log:
$ program-name 2> error.log
$ command1 2> error.log
For example, use the grep command for recursive search in the $HOME directory and redirect all errors (stderr) to a file name grep-errors.txt as follows:
$ grep -R ‘MASTER’ $HOME 2> /tmp/grep-errors.txt
$ cat /tmp/grep-errors.txt
Sample outputs:

Redirecting the standard error (stderr) and stdout to file

Use the following syntax:
$ command-name &>file
We can als use the following syntax:
$ command > file-name 2>&1
We can write both stderr and stdout to two different files too. Let us try out our previous grep command example:
$ grep -R ‘MASTER’ $HOME 2> /tmp/grep-errors.txt 1> /tmp/grep-outputs.txt
$ cat /tmp/grep-outputs.txt

Redirecting stderr to stdout to a file or another command

Here is another useful example where both stderr and stdout sent to the more command instead of a file:
# find /usr/home -name .profile 2>&1 | more

Redirect stderr to stdout

Use the command as follows:
$ command-name 2>&1
$ command-name > file.txt 2>&1
## bash only ##
$ command2 &> filename
$ sudo find / -type f -iname «.env» &> /tmp/search.txt
Redirection takes from left to right. Hence, order matters. For example:
command-name 2>&1 > file.txt ## wrong ##
command-name > file.txt 2>&1 ## correct ##

How to redirect stderr to stdout in Bash script

A sample shell script used to update VM when created in the AWS/Linode server:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Our last example uses the exec command and FDs along with trap and custom bash functions:

Want both stderr and stdout to the terminal and a log file too?

Try the tee command as follows:
command1 2>&1 | tee filename
Here is how to use it insider shell script too:

Conclusion

In this quick tutorial, you learned about three file descriptors, stdin, stdout, and stderr. We can use these Bash descriptors to redirect stdout/stderr to a file or vice versa. See bash man page here:

Operator Description Examples
command>filename Redirect stdout to file “filename.” date > output.txt
command>>filename Redirect and append stdout to file “filename.” ls -l >> dirs.txt
command 2>filename Redirect stderr to file “filename.” du -ch /snaps/ 2> space.txt
command 2>>filename Redirect and append stderr to file “filename.” awk ‘< print $4>‘ input.txt 2>> data.txt
command &>filename
command >filename 2>&1
Redirect both stdout and stderr to file “filename.” grep -R foo /etc/ &>out.txt
command &>>filename
command >>filename 2>&1
Redirect both stdout and stderr append to file “filename.” whois domain &>>log.txt

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

What this mean?
$ command > file-name 2>&1

This means redirect stdout to file-name, with that in mind redirect stderr t stdout.
This will lead to both stderr and stdout go to file-name.

Sayed: that line means execute the command while redirecting both stdout and stderr to a file given by file-name.

A slightly more correct is:
The output of the ‘command’ is redirected to a ‘file-name’ and the error chanel (that is the ‘2’ is redirected to a pointer (?) of the output (‘&1’).
So stderr goes to the stdout and that goes to the file.

Actually it means “first redirect STDERR to STDOUT, so any errors printed out on STDERR should go to STDOUT. Then, execute ‘command’ and redirect its STDOUT to ‘file-name’” – keeping in mind that at this point STDOUT will also contain whatever is written to STDERR because of the earlier redirection.

Incorrect.
There are two incorrect concepts in your answer.

First is: the redirection happens from left to right. This means that the STDOUT is redirected first.
(When you have > without a stream number, it actually have an implicit 1)
And only after STDERR is redirected to “the same place STDOUT is pointing”, meaning, ‘file-name’

Second wrong concept with your answer is: There are no connection between the descriptors. Changing STDOUT after STDERR had been redirected to STDOUT won’t change STDERR.
It will make STDERR point to STDOUT and then change STDOUT to something else (without touching STDERR)
Here is a more detailed tutorial covering both those misconceptions
http://wiki.bash-hackers.org/howto/redirection_tutorial

I like the &>file one. but not for every stiuation.

In pre-bash4 days you HAD to do it this way:

cat file > file.txt 2>&1

now with bash 4 and greater versions… you can still do it the old way …but …

cat file &> file.txt

The above is bash4+ … some OLD distros may use prebash4 but I think they are alllong gone by now. Just something to keep in mind.

I really love: “ command2>&1 | tee logfile.txt

because tee log’s everything and prints to stdout . So you stil get to see everything! You can even combine sudo to downgrade to a log user account and add date’s subject and store it in a default log directory 🙂

Hi! good explanation, I’d like to make a function on C that redirects STDIN and SDTOUT to an script, how can I do that, I mean, the exist a library’s on C to put terminal sintaxis on C?, how would you start to do it? I’m very lost with this. Thankyou!

Источник

Читайте также:  Как поставить лицензионный windows
Оцените статью