Как завершить процесс регистрации в сценарии оболочки без остановки сценария? - PullRequest
1 голос
/ 11 апреля 2019

Я работаю со сценарием оболочки для запуска моего анализа.Чтобы убедиться, что я могу подтвердить, что правильные команды были выполнены, я записываю полный вывод STDOUT / STDERR в файл

Мой скрипт выглядит так:

#!/bin/bash

# Here are some pliminary stuff

echo " this goes still to the STDOUT to control the begining of the script"

#### execute all output to log files
# to set a log file, where all echo command will be redirected into.
touch $projectName\_logfile.txt # creating the log file
exec &> $projectName\_logfile.txt # direct all output to the log file

echo "1. These steps should be written to the log file"

# exit 
# exec >&-

echo "2. 2. these steps should be written to the STDOUT again!"

# The script should be able to continue here ...

Как вы можете видетьЯ пробовал использовать команду exit и закрыть дескриптор файла, используя exec снова.Но оба не смогли.

Буду признателен за вашу помощь, чтобы понять, как закрыть соединение с файлом журнала и перенаправить все обратно в STDOUT / STDERR.

спасибо Assa

1 Ответ

1 голос
/ 11 апреля 2019

Я бы лучше подумал:

echo "to out 1"
{
  echo "to log 1"
  echo "to log 2"
} &> ./_logfile.txt 
echo "to out 2"

В любом случае, если Вам все еще нужно использовать Ваш подход, Вам необходимо сохранить оригинальные файловые дескрипторы:

exec 3<&1 # save original stdout to 3
exec 4<&2 # save original stderr to 4

А затем восстановить:

exec 1>&3 # restore original stdout
exec 2>&4 # restore original stderr

Ваш пример:

#!/bin/env bash

echo " this goes still to the STDOUT to control the begining of the script"

touch ./_logfile.txt # touch the log file
exec 3<&1 # save original stdout to 3
exec 4<&2 # save original stderr to 4
exec &> ./_logfile.txt # direct all out and err to the log file

echo "1. These steps should be written to the log file"

exec 1>&3 # restore original stdout
exec 2>&4 # restore original stderr

echo "2. 2. these steps should be written to the STDOUT again!"

# The script should be able to continue here ...
...