파이프 할당 변수

파이프 할당 변수

간단하게 유지하기 위해 다음을 수행하고 싶습니다.

echo cart | assign spo;
echo $spo  

출력: 장바구니

그런 assign애플리케이션이 존재하나요?

나는 교체를 사용하여 이 작업을 수행하는 모든 방법을 알고 있습니다.

답변1

사용하는 경우 다음과 같이 할 수 있습니다 bash.

echo cart | while read spo; do echo $spo; done

불행히도 변수 "spo"는 while-do-done 루프 외부에 존재하지 않습니다. while 루프에서 원하는 것을 달성할 수 있다면 괜찮습니다.

실제로 ATT ksh(pdksh 또는 mksh 아님) 또는 멋진 zsh에서 위에서 작성한 내용을 거의 정확하게 수행할 수 있습니다.

% echo cart | read spo
% echo $spo
cart

따라서 또 다른 해결책은 ksh 또는 zsh를 사용하는 것입니다.

답변2

echo cart | { IFS= read -r spo; printf '%s\n' "$spo"; }

이는 한 줄만 출력하는 한 작동합니다( echo후행 개행 없이 출력을 변수에 저장).spoecho

언제든지 다음과 같이 할 수 있습니다.

assign() {
  eval "$1=\$(cat; echo .); $1=\${$1%.}"
}
assign spo < <(echo cart)

다음 해결 방법은 bash스크립트 내에서는 작동하지만 bash프롬프트에서는 작동하지 않습니다.

shopt -s lastpipe
echo cat | assign spo

또는:

shopt -s lastpipe
whatever | IFS= read -rd '' spo

whateverbash에 출력의 이전 NUL 문자까지 저장합니다 $spo.

또는:

shopt -s lastpipe
whatever | readarray -t spo

출력을 whatever다음에 저장하십시오.$spo 대량으로(배열 요소당 하나의 행)

답변3

질문을 올바르게 이해했다면 stdout을 변수에 전달하고 싶습니다. 적어도 그것이 내가 찾고 있던 것이고 결국 여기까지 왔습니다. 그러니 나와 같은 운명을 공유하고 있는 분들을 위해:

spa=$(echo cart)

cart변수에 할당되었습니다 $spa.

답변4

이것이 문제에 대한 나의 해결책입니다.

# assign will take last line of stdout and create an environment variable from it
# notes: a.) we avoid functions so that we can write to the current environment
#        b.) aliases don't take arguments, but we write this so that the "argument" appears
#            behind the alias, making it appear as though it is taking one, which in turn
#            becomes an actual argument into the temporary script T2.
# example: echo hello world | assign x && echo %x outputs "hello world"
alias assign="tail -1|tee _T1>/dev/null&&printf \"export \\\$1=\$(cat _T1)\nrm _T*\">_T2&&. _T2"

관련 정보