启动新的 bash 会话背景

Wil*_*iam -1 bash alias

是否可以创建一个名为new_bash允许我执行以下操作的命令?

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

new_bash test
file1
new_bash new_command
file1
Run Code Online (Sandbox Code Playgroud)

PSk*_*cik 6

##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>&-
Run Code Online (Sandbox Code Playgroud)

您的函数需要维护全局状态。您的函数需要检查状态是否已设置,如果尚未设置(可能通过检查变量是否存在)进行设置。在设置之后或者如果状态存在,它只需要echo它的参数 ( "$@")&3或者你打开管道的任何文件描述符。

创建三个函数可能是一个更好的主意(它会更有效一点):

init_new_bash
new_bash
end_new_bash
Run Code Online (Sandbox Code Playgroud)

示例(需要更好的信号处理):

#!/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;}
Run Code Online (Sandbox Code Playgroud)