- BASH Shell Redirect Output and Errors To /dev/null
- Syntax to redirect error and output messages to /dev/null
- Redirect both standard error and standard out messages to a log file
- Want to close stdout and stderr for the command being executed on a Linux/Unix/BSD/OSX bash shell?
- Explained: Input, Output and Error Redirection in Linux
- Stdin, stdout and stderr
- The output redirection
- The output file is created beforehand
- Append instead of clobber
- Pipe redirection
- Remember the stdout/stdin is a chunk of data, not filenames
- The input redirection
- Stderr redirection examples
- Summary
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.
Источник
Explained: Input, Output and Error Redirection in Linux
If you are familiar with the basic Linux commands, you should also learn the concept of input output redirection.
You already know how a Linux command functions. It takes an input and gives you an output. There are a few players in the scene here. Let me tell you about them.
Stdin, stdout and stderr
When you run a Linux command, there are three data stream that play a part in it:
- Standard input (stdin) is the source of input data. By default, stdin is any text entered from the keyboard. It’s stream ID is 0.
- Standard output (stdout) is the outcome of command. By default, it is displayed on the screen. It’s stream ID is 1.
- Standard error (stderr) is the error message (if any) produced by the commands. By default, stderr is also displayed on the screen. It’s stream ID is 2.
These streams contain the data in plain text in what’s called buffer memory.
Think of it as water stream. You need a source for water, a tap for example. You connect a pipe to it and you can either store it in a bucket (file) or water the plants (print it). You can also connect it to another tap, if needed. Basically, you are redirecting the water.
Linux also has this concept of redirection, where you can redirect the stdin, stdout and stderr from its usual destination to another file or command (or even peripheral devices like printers).
Let me show how redirection works and how you can use it.
The output redirection
The first and simplest form of redirection is output redirection also called stdout redirection.
You already know that by default, the output of a command is displayed on the screen. For example, I use the ls command to list all the files and this is the output I get:
With output redirection, you can redirect the output to a file. If this output files doesn’t exist, the shell will create it.
For example, let me save the output of the ls command to a file named output.txt:
The output file is created beforehand
What do you think the content of this output file should be? Let me use the cat command to show you a surprise:
Did you notice that the inclusion of output.txt there? I deliberately chose this example to show you this.
The output file to which the stdout is redirected is created before the intended command is run. Why? Because it needs to have the output destination ready to which the output will be sent.
Append instead of clobber
One often ignored problem is that if you redirect to a file that already exists, the shell will erase (clobber) the file first. This means the existing content of the output file will be removed and replaced by the output of the command.
You can append, instead of overwriting it, using the >> redirection syntax.
Tip: You can forbid clobbering in current shell session using: set -C
Why would you redirect stdout? You can store the output for future reference and analyze it later. It is specially helpful when the command output is way too big and it takes up all of your screen. It’s like collecting logs.
Pipe redirection
Before you see the stdin redirection, you should learn about pipe redirection. This is more common and probably you’ll be using it a lot.
With pipe redirection, you send the standard output of a command to standard input of another command.
Let me show you a practical example. Say, you want to count the number of visible files in the current directory. You can use ls -1 (it’s numeral one, not letter L) to display the files in the current directory:
You probably already know that wc command is used for counting number of lines in a file. If you combine both of these commands with pipe, here’s what you get:
With pipe, both commands share the same memory buffer. The output of the first command is stored in the buffer and the same buffer is then used as input for the next command.
You’ll see the result of the last command in the pipeline. That’s obvious because the stdout of earlier command(s) is fed to the next command(s) instead of going to the screen.
Pipe redirection or piping is not limited to connecting just two commands. You may connect more commands as long as the output of one command can be used as the input of the next command.
Remember the stdout/stdin is a chunk of data, not filenames
Some new Linux users get confused while using the redirection. If a command returns a bunch of filenames as output, you cannot use those filenames as argument.
For example, if you use the find command to find all the files ending with .txt, you cannot pass it through pipe to move the found files to a new directory, not directly like this:
This is why you’ll often see find command used in conjugation with exec or xargs command. These special commands ‘convert the text with bunch of filenames into filename’ that can be passed as argument.
The input redirection
You can use stdin redirection to pass the content of a text file to a command like this:
You won’t see stdin being used a lot. It’s because most Linux commands accept filenames as argument and thus the stdin redirection is often not required.
Take this for example:
The above command could have just been head filename.txt (without the or >> redirection symbol that you used for stdout redirection.
But how do you distinguish between the stdout and stderr when they are both output data stream? By their stream ID (also called file descriptor).
Data Stream | Stream ID |
---|---|
stdin | 0 |
stdout | 1 |
stderr | 2 |
-t, | –list |
-u, | –update |
-x, | –extract, –get |
-j, | –bzip2 |
-z, | –gzip, –gunzip, –ungzip |
By default when you use the output redirection symbol >, it actually means 1>. In words, you are saying that data stream with ID 1 is being outputted here.
When you have to redirect the stderr, you use its ID like 2> or 2>>. This signifies that the output redirection is for data stream stderr (ID 2).
Stderr redirection examples
Let me show it to you with some examples. Suppose you just want to save the error, you can use something like this:
That was simple. Let’s make it slightly more complicated (and useful):
In the above example, the ls command tries to display two files. For one file it gets success and for the other, it gets error. So what I did here is to redirect the stdout to ouput.txt (with >) and the stderr to the error.txt (with 2>).
You can also redirect both stdout and stderr to the same file. There are ways to do that.
In the below example, I first send the stderr (with 2>>) to combined.txt file in append mode. And then, the stdout (with >>) is sent to the same file in append mode.
Another way, and this is the preferred one, is to use something like 2>&1. Which can be roughly translated to “redirect stderr to the same address as stdout”.
Let’s take the previous example and this time use the 2>&1 to redirect both of the stdout and stderr to the same file.
Keep in mind that you cannot use 2>>&1 thinking of using it in append mode. 2>&1 goes in append mode already.
You may also use 2> first and then use 1>&2 to redirect stdout to same file as stderr. Basically, it is “>&” which redirects one out data stream to another.
Summary
- There are three data streams. One input, stdin (0) and two output data streams stdout (1) and stderr (2).
- Keyboard is the default stdin device and the screen is the default output device.
- Output redirection is used with > or >> (for append mode).
- Input redirection is used with or 2>>.
- The stderr and stdout can be combined using 2>&1.
Since you are learning about redirection, you should also know about the tee command. This command enables you to display to standard output and save to file simultaneously.
I hope you liked this detailed guide on redirection in Linux. If you still have doubts or if you have suggestions to improve this article, please let me know in the comment section.
Источник