Bash streams: Difference between revisions

From wikinotes
 
Line 92: Line 92:
programA | programB
programA | programB
</source>
</source>
echo to stderr
<syntaxhighlight lang="bash">
# echoes to stderr only, not stdout
{ >&2 echo "[ERROR] foo was barred"; }
</syntaxhighlight>
</blockquote><!-- redirect streams -->
</blockquote><!-- redirect streams -->

Latest revision as of 02:19, 25 January 2023

pipes

Most of the bash Programs: coreutils are designed to used together in a pipeline. The output of one can be redirected to the input of another.

Example

echo '
apple
orange#> orange#> orange
banana'
#> apple
#> orange
#> banana

echo '
apple
orange
banana' | grep n
#> orange
#> banana

echo '
apple
orange
banana' | grep n | grep b
#> banana

stdin, stdout, stderr

Your terminal interacts with 3 streams:

  • stdout: print, echo, etc. text intended for the user
  • stderr: logger output, debug info
  • stdin: text piped into the current process

stdin

setting stdin

program < file           # pipe 'file' contents to 'program's stdin
cat file.txt | program   # pipe 'file' contents to 'program's stdin

read from stdin (by line)

while read line; do
    echo $line
done < /dev/stdin

get user input

# accepts keys until newline (enter)
read user_input
echo $user_input

# get user input, with prompt
read -p '>>> ' user_input

stdout, stderr

# stdout
program  >    stdout.log
program 1>    stdout.log

# stderr
program 2>    stderr.log

# stdout & stderr
program 2>&1  stdout_stderr.log
program &>    stdout_stderr.log

redirecting streams

redirect one stream into another

program 2>&1            # redirect stderr into stdout

redirect programA's stdout to programB's stdin

programA | programB

echo to stderr

# echoes to stderr only, not stdout
{ >&2 echo "[ERROR] foo was barred"; }