新しいbashセッションコンテキストの開始

新しいbashセッションコンテキストの開始

new_bash次のことができるコマンドを生成できますか?

new_bash alias test="ls"
new bash alias new_command="ls"

new_bash test
file1
new_bash new_command
file1

ベストアンサー1

##Background:

cd $(mktemp -d)
> file1

##Setup state (background bash + pipe)
pipeDir=$(mktemp -d)
mkfifo $pipeDir/p #pipe for communicating with the shell
#start the shell in the background, make it read from the pipe, and disable I/O buffering
stdbuf -i0 -o0 bash < $pipeDir/p & 
#open the pipe from the other end on fd 3 (or another fd)
exec 3>$pipeDir/p && 
rm -rf "$pipeDir" #don't need the directory or the physical link to the pipe anymore

##Now you can communicate with the shell
echo ls >&3
#Ouptuts: file1

#This is how you end it all
exec 3>&-

関数はグローバル状態を維持する必要があります。関数では、状態が設定されていることを確認し、まだ設定されていない場合は状態を設定する必要があります(変数が存在することを確認して)。設定または状態が存在する場合は、対応する引数echo"$@"&3またはパイプを開いたファイル記述子のみを使用してください。

3つの機能を作成する方が良いアイデアかもしれません(より効率的です)。

init_new_bash
new_bash
end_new_bash

はい(より良い信号処理が必要です):

#!/bin/sh 
#^will work in bash also
init_new_bash(){
    set -e #all must succeed
    pipeDir=$(mktemp -d)  
    mkfifo "$pipeDir/p" 

    stdbuf -i0 -o0 bash < "$pipeDir"/p & 
    bashPid=$! 

    exec 3>"$pipeDir/p"
    rm -rf "$pipeDir" 
    set +e
}
new_bash(){ echo "$@" >&3; }
end_new_bash(){ exec 3>&-; wait "$bashPid"; }

##Test run:
init_new_bash && {

   new_bash echo hello world
   new_bash ls

end_new_bash;}

おすすめ記事