该脚本基本上具有用户应该阅读的输出。我在想这个:
#!/bin/bash
#cd to the script dir if executed from outside
SCRIPT_PATH=$(dirname "$(readlink -f "$0")")
cd "$SCRIPT_PATH"
if [ ! -t 1 ]; then #not from terminal
SCRIPT=$(basename "$(readlink -f "$0")")
x-terminal-emulator --profile "$USER" --working-directory "$SCRIPT_PATH" -e "./$SCRIPT" &
exit 0
fi
echo "output"
#keep terminal open
bash
但这有一个问题,如果您尝试关闭新终端的窗口(当从 nautilus 执行时,pgrep 表示只有一个 bash 进程)或“旧”终端(当从已打开的终端执行时,pgrep 表示)二bash 进程),“此终端中仍有一个进程正在运行。关闭终端将杀死它。”
我正在寻找一个完整的解决方案:可以从开放的终端运行,可以从 nautilus 或其他文件管理器运行,始终允许用户读取输出,退出时不会让进程挂起,并且不会显示警告用户无意中关闭了窗口。
我很确定“进程”使可见控制台显示警告是bash
在最后一行,但如果脚本是从 nautilus 运行的话,bash 是唯一允许看到回显的东西。
答案1
略有改进:用于trap
退出时提示:
# some scripts like are meant to be run by clicking on
# them in the file manager. This function runs the script in an X
# terminal if it isn't in a terminal already.
run_in_terminal() {
# run in a new terminal if not already
if [ ! "${RUNNING_IN_TERMINAL:-}" -a ! -t 1 -a "${DISPLAY:-}" ]; then
RUNNING_IN_TERMINAL=1 exec x-terminal-emulator -e "$@"
fi
# wait for prompt to close the terminal
if [ "${RUNNING_IN_TERMINAL:-}" ]; then
exit_prompt() {
echo
read -p "Finished. Press any key to close..." -n 1
}
trap exit_prompt EXIT
fi
}
run_in_terminal "$0" "$@"
答案2
可以通过执行以下操作来解决此问题:
SCRIPT_PATH=$(dirname "$(readlink -f "$0")")
cd "$SCRIPT_PATH"
if [ ! -t 1 ]; then #not from terminal
SCRIPT=$(basename "$(readlink -f "$0")")
SUBPROC=1 x-terminal-emulator --profile "$USER" --working-directory "$SCRIPT_PATH" -e "./$SCRIPT" &
exit 0
fi
echo "output"
...
[[ -v SUBPROC ]] && read -p "Press any key to exit" -n1 junk
有点烦人,但可以肯定。