Sha*_*rad 9 bash shell zsh exec
我想运行任何作为参数给出的程序,通过shell然后希望将shell保留为交互式shell以便稍后使用.
#!/bin/bash
bash -i <<EOF
$@
exec <> /dev/tty
EOF
Run Code Online (Sandbox Code Playgroud)
但它不适用于zsh
#!/bin/bash
zsh -i <<EOF
$@
exec <> /dev/tty
EOF
Run Code Online (Sandbox Code Playgroud)
如果有人知道更多改进的方法,请告诉我.
方法 1:bash、zsh 和其他一些 shellENV在通常的 rc 文件之后、交互式命令或要运行的脚本之前读取名称位于环境变量中的文件。然而,bash 仅在作为 sh 调用时才执行此操作,而 zsh 仅在作为 sh 或 ksh 调用时执行此操作,这是相当有限的。
temp_rc=$(mktemp)
cat <<'EOF' >"$temp_rc"
mycommand --option
rm -- "$0"
EOF
ENV=$temp_rc sh
Run Code Online (Sandbox Code Playgroud)
方法 2:使 shell 读取不同的 rc 文件,该文件获取通常的 rc 文件并包含对要运行的程序的调用。例如,对于 bash:
temp_rc=$(mktemp)
cat <<'EOF' >"$temp_rc"
mycommand --option
if [ -e ~/.bashrc ]; then . ~/.bashrc; fi
rm -- "$0"
EOF
bash --rcfile "$temp_rc"
Run Code Online (Sandbox Code Playgroud)
对于zsh来说,该文件必须被调用.zshrc,只能指定不同的目录。
temp_dir=$(mktemp -d)
cat <<'EOF' >"$temp_dir/.zshrc"
mycommand --option
if [ -e ~/.zshrc ]; then . ~/.zshrc; fi
rm -- $0; rmdir ${0:h}
EOF
ZDOTDIR=$temp_dir zsh
Run Code Online (Sandbox Code Playgroud)