모듈 식 스크립트를 만들려고합니다. 단일 스크립트에서 호출되는 여러 스크립트 / 명령이 있습니다.
각 개별 명령의 출력 앞에 접두사를 붙이고 싶습니다.
예 :
내 파일은 allcommands.sh / command1.sh / command2.sh입니다.
command1.sh 출력
file exists
file moved
command2.sh 출력
file copied
file emptied
allcommands.sh 는 스크립트 command1.sh 및 command2.sh를 실행합니다.
이 두 스크립트의 각 출력 앞에 다음과 같이 붙이고 싶습니다.
[command1] file exists
[command1] file moved
[command2] file copied
[command2] file emptied
답변
allcommands.sh에서 수행중인 작업은 다음과 같습니다.
command1.sh
command2.sh
그냥
command1.sh | sed "s/^/[command1] /"
command2.sh | sed "s/^/[command2] /"
답변
최소한의 예 allcommands.sh
:
#!/bin/bash
for i in command{1,2}.sh; do
./"$i" | sed 's/^/['"${i%.sh}"'] /'
done
원하는 문자열을 사용 command1.sh
하여 command2.sh
실행 가능한 디렉토리와 동일한 디렉토리 echo
에 쉘 출력을 제공합니다.
$ ./command1.sh
file exists
file moved
$ ./command2.sh
file copied
file emptied
$ ./allcommands.sh
[command1] file exists
[command1] file moved
[command2] file copied
[command2] file emptied
빠른 sed
고장
sed 's/^/['"${i%.sh}"'] /'
s/
“정규 패턴 일치 및 교체”모드로 들어갑니다.^/
“모든 줄의 시작과 일치”를 의미${i%.sh}
쉘 컨텍스트에서 발생하며 ”$i
, 그러나 접미사 제거.sh
“['"${i%.sh}"'] /
처음에는 a를 인쇄 한[
다음 인용 된 컨텍스트를 종료하여$i
쉘 에서 변수를 가져온 다음]
및 공백으로 다시 입력 합니다.