
내 bash 파일에는 다음과 같은 특정 작업을 수행하도록 되어 있는 여러 스크립트가 있습니다.
#!bin/bash
yum -y update
service restart nginx
yum install atop
cat /var/log/somelog.log > /home/cron/php/script
계속 진행되지만 문제는 각 작업이 실행될 때마다 bash가 출력을 표시한다는 것입니다. 예를 들어 service restart nginx
일부 메시지를 출력합니다. 이 메시지를 모두 숨기고 싶습니다. 이를 달성하기 위해 일반적으로 허용되는 방법은 무엇입니까? 왜냐하면 STDOUT을 로 리디렉션하려고 하는데 /dev/null
실행해야 할 연속 작업이 50개가 넘는다는 점을 고려하면, 이는 너무 많은 작업을 수행해야 한다는 것을 의미하기 /dev/null
때문에 어떤 이유로든 이 방법이 그다지 효율적이지 않은 것 같습니다.
답변1
모든 출력을 블록으로 리디렉션합니다.
(
yum -y update
service restart nginx
yum install atop
cat /var/log/somelog.log > /home/cron/php/script
) > /dev/null 2>&1
답변2
stdout 및 stderr에 대한 파일 설명자를 저장하고 덮어쓰며 프로그램 실행 후 복원할 수 있습니다.
exec 3>&1
exec 4>&2
exec 1>/dev/null
exec 2>/dev/null
./script-1
./script-2
...
./script-n
exec 1>&3
exec 2>&4
# delete the copies
exec 3>&-
exec 4>&-
답변3
실행 중인 명령의 모든 출력(출력 및 오류 모두)을 숨기고 싶지만 여전히 메시지를 직접 인쇄할 수 있다면 Hauke Laging의 접근 방식이 확실히 좋은 방법입니다.
이를 통해 stdout(파일 설명자 1이라고도 함) 및 stderr(파일 설명자 2라고도 함)에 대한 참조를 유지하고 이를 /dev/null로 리디렉션할 수 있지만 메시지를 표시하려는 경우 계속 사용할 수 있습니다. 나는 그것이 무엇을 하고 있는지 정확히 설명하기 위해 몇 가지 설명을 추가하고 싶었습니다.
exec 3>&1 # Open file descriptor 3, writing to wherever stdout currently writes
exec 4>&2 # Open file descriptor 4, writing to wherever stderr currently writes
exec 1>/dev/null # Redirect stdout to /dev/null, leaving fd 3 alone
exec 2>/dev/null # Redirect stderr to /dev/null, leaving fd 4 alone
# Programs won't show output by default; they write to fd 1 which is now /dev/null.
# This is because programs inherit file descriptors from the shell by default.
echo foo
# You can choose to show messages by having them write to fd 3 (old stdout) instead.
# This works by saying that echo's fd 1 (stdout) is the shell's fd 3.
echo bar >&3
# And when you're done you can reset things to how they were to start with
exec 1>&3 # Point stdout to where fd 3 currently points (the original stdout)
exec 2>&4 # Point stderr to where fd 4 currently points (the original stderr)
exec 3>&- # Close fd 3 (it now points to the same spot as fd 1, so we don't need it)
exec 4>&- # Close fd 4 (it now points to the same spot as fd 1, so we don't need it)
어떤 크기의 스크립트에서든 이것을 사용할 예정이고 일이 어떻게 진행되고 있는지에 대한 상태 업데이트를 자주 인쇄해야 하는 경우 원본 파일인 stdout 및 stderr에 echo "$@" >&3
메시지를 인쇄하는 도우미 함수를 만드는 것이 좋습니다. echo "$@" >&4
스크립트에&3
참조를 추가할 필요가 없습니다.&4
그리고이 bash-hackers.org 리디렉션 튜토리얼이와 같이 적당히 복잡한 리디렉션이 실제로 어떻게 작동하는지에 대한 좋은 시각적 설명입니다.