Перенаправить эхо в функции trap обратно на стандартный вывод

Debido a que está utilizando un heredoc citado, el shell no expande la variable de shell $hostname. Haga esto :pase la variable a esperar a través del entorno

export hostname
for hostname in ABCD123 ABCD234 ABCD445
do
    expect << 'EOS'
        set hos $env(hostname) ;# access the environment variable
        spawn ssh padmin@$hos
        expect "Password:"
        send "ABC1234\r"
        expect "$"
        send "oem_setup_env\r"
        expect "#"
        send "lsmcode -A | sed -e 's/^/$hos: /'\r"
        expect "#"
        send "exit\r"
        expect "$"
        send "exit\r"
        expect eof             ;# wait for the connection to close
EOS
done

Idiomáticamente, usa \rpara "presionar enter" para los comandos de envío.

2
04.06.2019, 22:37
1 ответ

[это больше комментарий, чем ответ; не совсем понятно, чего вы пытаетесь добиться]

set -eприведет к завершению вашего скрипта при ошибке, так что слишком поздно что-либо перенаправлять.

Возможно, вам нужно что-то подобное:

#! /bin/bash
set -o errtrace # let functions inherit the ERR trap
exec 3>&2       # save the original stderr into fd 3

on_error() {
        echo >&2 "An error occurred"    # still printed to the log the 1st time
        exec 2>&3       # switch back to the original stderr
        trap '' ERR     # disable ourselves
}
main() {
        trap on_error ERR
        no_such_command # this fail with an error
        no_such_command # again
        no_such_command # and again
}

main "$@" >/tmp/log 2>&1

при запуске:

$ bash /tmp/err
/tmp/err: line 13: no_such_command: command not found
/tmp/err: line 14: no_such_command: command not found
$ cat /tmp/log
/tmp/err: line 12: no_such_command: command not found
An error occurred

Сценарий OP изменен для вывода сообщения в исходный stderr и выхода при ошибке:

#!/usr/bin/env bash
set -o errtrace # let functions inherit the ERR trap
exec 3>&2       # save the original stderr

on_error()
{
  echo >&3 "An error occurred"
  exit 1
}

function main()
{
  trap on_error ERR
  # for looping over set of commands
  $command &> "$LOGFILE"
}

main "$@"

при запуске:

$ command=no_such_command LOGFILE=/tmp/log bash /tmp/jeg
An error occurred
$ cat /tmp/log
/tmp/jeg: line 15: no_such_command: command not found
0
27.01.2020, 22:26

Теги

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