NASutils Knowledge BaseUnofficialPolski

Bash · lesson 18 of 30 · Data, functions and the command lineSteer the output

> writes a new file or replaces the old one, >> adds, 2> takes the error output and << gives a command several lines.

Programming on the NAS › Bash in 30 lessons

18-redirect.sh Download 18-redirect.sh

#!/usr/app/TurboShell/bin/bash
echo "this goes to the screen"
echo "this goes to the error output" >&2
ls missing-folder 2>error.txt || echo "ls failed, its message is in error.txt"
echo "first" >list.txt
echo "second" >>list.txt
cat >letter.txt <<EOF
Dear ${1:-reader},
list.txt has $(wc -l <list.txt) lines.
EOF
cat letter.txt

Terminal

$ bash 18-redirect.sh 2>/dev/null
this goes to the screen
ls failed, its message is in error.txt
Dear reader,
list.txt has 2 lines.
$ bash 18-redirect.sh >/dev/null
this goes to the error output

Exercise

Write the errors and the output into one file.