Home > Software engineering >  Bash Redirects That I Don't Understand
Bash Redirects That I Don't Understand

Time:09-07

I have a variable called payload that points to a file and I have this line that is completely baffling me. Can anyone interpret this for me?

cat > $payload <&0

Above this line I also have other cryptic messages that I don't understand either. Perhaps you could help me with this at the same time.

exec 3>&1
exec 1>&2

CodePudding user response:

exec when given only redirections will set them for the remainder of the script.

If you do exec 1>/tmp/myfile, then any text that gets printed to stdout (or rather, file descriptor 1) will be sent to that file instead of your terminal. This is pretty handy for logging, particularly when you do something tricky like

exec 1> >(ts | tee -a /var/log/myscript.log)

You can also redirect a file descriptor to another file descriptor's destination. exec 3>&1 redirects fd 3 to whatever fd 1 is currently pointing to. The 2 exec calls set fd 3 to print to the current destination for fd 1 (probably /dev/stdout) and then stdout is redirected to stderr.

If you invoke that script like

bash myscript 2>/dev/null

Then you'll only see stuff printed like echo hello >&3


The cat <&0 is odd: by default cat reads from stdin if no filenames are given. We'd have to see more context to figure out that apparent redundancy.

  • Related