📝 Edit page
➕ Add page
Redirection
Writing stderr and stdout to files
Resources
- Redirection guide.
- Pipes and Redirection guide.
Send stderr and stdout to different files
$ COMMAND > stdout.txt 2> stderr.txt
Send stderr to stdout
Send any error output to the same place as where stdout
is going.
$ COMMAND 2> &1
This is not so useful in itself when just running in the console alone. But more useful when using crontab, tee
or writing to a file.
Write stderr and stdout to the same file
$ COMMAND &> stdout_and_sterr.txt
Or more verbosely. Send stdout
to a file and then send stderr
there too.
$ COMMAND > stdout_and_sterr.txt 2> &1
Apparently supported in all shells.
From askubuntu.com question.
Append output
Append just stdout
to a file.
$ COMMAND >> stdout_and_sterr.txt
Append stdout
and stderr
to a file.
$ COMMAND >> stdout_and_sterr.txt 2> &1
From SO question
Hide all output from a command
$ COMMAND &> /dev/null
Or
$ COMMAND > /dev/null 2> &1
e.g.
if command -v node &> /dev/null; then
echo 'Node is installed!'
else
echo 'Node is not installed :('
fi
Store file contents as a variable
$ CONTENT=$(< file.txt)
Write multi-line content to file
This is useful for adding instructions in docs to copy and paste a comamnd.
$ cat << EOF > hello.c
#include <stdio.h>
int main(int argc, char ** argv) {
printf("Hello, world!\n");
}
EOF
See the Strings Shell cheatsheet for more info on a Heredoc.