What does 1>&2 mean in shell? [duplicate]

2019-06-14 20:04发布

问题:

This question already has an answer here:

  • echo that outputs to stderr 14 answers
  • In the shell, what does “ 2>&1 ” mean? 15 answers

Pretty noob question, what does the 1>&2 do in this script?

if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

回答1:

That redirects the line "This script must be run as root" from standard out (STDOUT) to standard error output (STDERR).

It's a easy way to print an error message to STDERR - this matters if you run the bash script from another script (like crontab), matters much less if you run it from the command line driectly since your terminal will show both STDOUT and STDERR.

See also echo that outputs to stderr