简体   繁体   中英

How to redirect output to STDERR?

Suppose that I passed in 2 parameters to my function. How can I redirect a message to stderr?

#!/bin/bash
if [ $# = 0 ]; then
    dir="."
elif [ $# = 1 ]; then
    dir=$1
elif [ $# -ge 2 ]; then
    echo "Too many operands." 2>> err.txt //???
    exit 1
fi

Just add >&2 to the statement producing the output:

echo "Too many operands." >&2

and if you want it to be appended to a file named err.txt too:

echo "Too many operands." | tee -a 'err.txt' >&2

FWIW I'd write your code using a case statement instead of nested if s (and tidy up a couple of things):

#!/bin/env bash
case $# in
    0 ) dir='.' ;;
    1 ) dir="$1" ;;
    * ) printf 'Too many operands: %d\n' "$#" | tee -a 'err.txt' >&2
        exit 1 ;;
esac

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM