Общие сведения о перенаправлении ввода-вывода в Bash

Решил сам

n=5
echo $(date -v -${n}d)
1
02.12.2020, 19:04
1 ответ

В форме, которую вы написали изначально, где команда просто cmd -options... 2>&1 1>&3, это не имеет особого смысла, так как фактически и stderr, и stdout перенаправляются на stdout. Так что 1>&3не нужен.

Но тот пример, о котором вы говорили, — это другой случай. У нас есть variable=$(cmd -options... 2>&1 1>&3). Конструкция $(command)сама по себе перенаправляет стандартный вывод command, чтобы его можно было захватить и поместить в переменную. Таким образом, в этом случае первый stderr из commandперенаправляется на , уже перенаправленный stdout (2>&1), т.е. будет помещен в переменную, и после этого stdout из commandперенаправляется на исходный stdout до перенаправления, хранящийся в дескрипторе 3(1>&3). Эффект заключается в том, что stderr из commandбудет помещен в переменную, а stdout будет отображаться нормально -как бы противоположно «обычному» variable=$(command)случаю, когда stdout помещается в переменную и отображается stderr. Это довольно хорошо объяснено на той же странице, на которую вы ссылаетесь :

.

At first glance, the redirection may seem nonsensical. First, we duplicate file descriptor 1 (stdout) to descriptor 3 using exec (this was covered in More Redirection) to create a backup copy of descriptor 1.

The next step is to perform a command substitution and assign the output of a the dialog command to the variable result. The command includes redirections of descriptor 2 (stderr) to be the duplicate of descriptor 1 and lastly, descriptor 1 is restored to its original value by duplicating descriptor 3 which contains the backup copy. What might not be immediately apparent is why the last redirection is needed. Inside the subshell, standard output (descriptor 1) does not point to the controlling terminal. Rather, it is pointing to a pipe that will deliver its contents to the variable result. Since dialog needs standard output to point to the terminal so that it can display the input box, we have to redirect standard error to standard output (so that the output from dialog ends up in the result variable), then redirect standard output back to the controlling terminal.

1
18.03.2021, 22:45

Теги

Похожие вопросы