스크립트에서 쉘을 여러 번 변경

스크립트에서 쉘을 여러 번 변경

나는 명령 목록을 가져와서 하나씩 실행하고 출력을 표시할 수 있는 스크립트를 원합니다. 문제는 특정 명령이 새 셸을 시작하여 후속 명령에 영향을 미친다는 것입니다. 이라는 파일에 몇 가지 샘플 입력이 있습니다 commands.

echo "current shell: $0"
ksh
echo "current shell: $0"
exit
echo "current shell: $0"

test3.sh명명된 파이프를 사용하여 명령을 보내는 스크립트가 있습니다 .

#! /usr/bin/env bash

# Create a pipe for processing commands
rm -f shell-pipe
mkfifo shell-pipe

# Set up a bash shell to process the commands sent to the pipe
(tail -f shell-pipe | bash) &

while IFS='' read -r command; do
  echo ">>> sending command: $command"
  echo $command > shell-pipe
  sleep 1
done

# Close the pipe and delete it
fuser -TERM -k shell-pipe > /dev/null
rm shell-pipe

효과가있다.

$ ./test3.sh < commands
>>> sending command: echo "current shell: $0"
current shell: bash
>>> sending command: ksh
>>> sending command: echo "current shell: $0"
current shell: ksh
>>> sending command: exit
>>> sending command: echo "current shell: $0"
current shell: bash

하지만 명령이 완료되는 데 시간이 얼마나 걸릴지 미리 알 수 없으므로명령이 완료되었는지 확인하는 방법이 필요합니다.. 그래서 응답을 위해 별도의 명명된 파이프를 설정했습니다.

$ cat test4.sh
#! /usr/bin/env bash

# Create a pipe for processing commands
rm -f shell-pipe response-pipe
mkfifo shell-pipe response-pipe

# Set up a bash shell to process the commands sent to the pipe
(tail -f shell-pipe | bash > response-pipe) &

while IFS='' read -r command; do
  echo ">>> sending command: $command"
  echo $command > shell-pipe
  echo "...waiting for response..."
  echo "<<< reponse: " $(cat response-pipe)
done

# Close the pipe and delete it
fuser -TERM -k shell-pipe > /dev/null
rm shell-pipe response-pipe

불행히도 이것이 중단되어 결국 Ctrl-c를 사용해야 합니다.

$ ./test4.sh < commands
>>> sending command: echo "current shell: $0"
...waiting for response...
^C

명령 을 사용해 보았지만 exec도움이 되지 않았습니다. 이 예에서는 Python을 사용 bash하지만 다른 셸인 Python이나 Haskell을 사용해도 좋습니다.

답변1

이것을(또는 한 번에 한 줄씩 입력을 처리하는 쉘)로 실행하면 bash < file다음과 같이 작동합니다.read

$ cat file
echo "current shell: $0"
ksh
echo "current shell: $0"
exit
echo "current shell: $0"
$ bash < file
current shell: bash
current shell: ksh
current shell: bash
$ zsh < file
current shell: zsh
current shell: ksh
current shell: zsh

dash( 읽는 내용을 해석하기 전에 전체 파일(최소 8KiB 청크)을 읽는 작업은 작동하지 않으므로 (bash 또는 ksh 검색을 수행하지 않고) ksh는 시작 시 읽을 내용이 없습니다.

호출된 명령(셸뿐만 아니라)이 표준 입력을 읽는 경우 스크립트에서도 읽습니다.

export VAR=before
echo "$0 $VAR"
ksh
echo "$0 $VAR"
read VAR
after
echo "$0 $VAR"
exit
echo "$0 $VAR"

당신은 얻을 것이다:

bash before
ksh before
ksh after
bash before

관련 정보