Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Eduardo Issao Ito
Eduardo Issao Ito

Posted on

     

Output redirection with bash

The command below generates output in different I/O streams: error messages should go tostderr stream and "normal" messages tostdout stream. But if you run it in a terminal both streams are written to the screen:

$ ls -d /tmp nothingls: cannot access 'nothing': No such file or directory/tmp

You can redirect the output to a file. Note that the error message is written in the screen, not in in the file:

$ ls -d /tmp nothing > stdout.txtls: cannot access 'nothing': No such file or directory$ cat stdout.txt/tmp

Or you can redirect only the error message:

$ ls -d /tmp nothing 2> stderr.txt/tmp$ cat stderr.txtls: cannot access 'nothing': No such file or directory

Also, you can redirect both streams at the same time todistinct files:

$ ls -d /tmp nothing 2> stderr.txt > stdout.txt$ cat stderr.txt ls: cannot access 'nothing': No such file or directory$ cat stdout.txt /tmp

Or you can redirect everything to thesame file:

$ ls -d /tmp nothing &> all.txt$ cat all.txt ls: cannot access 'nothing': No such file or directory/tmp

Another possibility is to redirect stderr to stdout. It can be useful when you are passing data to another command. In the example below, both lines are sent to stdout andwc will count 2 lines:

$ ls -d /tmp nothing 2>&1 | wc -l2

Redirecting stdout to stderr is also possible. In this case both lines are sent to stderr that is displayed at the terminal screen, and nothing is sent to stdout, sowc will count 0 lines:

$ ls -d /tmp nothing 1>&2 | wc -l0ls: cannot access 'nothing': No such file or directory/tmp

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
ondrejs profile image
Ondrej
Philosophy, maths & human rights focused technology
  • Location
    .onion
  • Joined

I would just add that it should work on most POSIX shells, not only for Bash.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software architect, developer, learner.
  • Location
    São Paulo
  • Joined

More fromEduardo Issao Ito

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp