如何判断用户是否选择了"在终端中运行"

Rya*_*wis 4 linux bash ubuntu

当您双击bash脚本时,Ubuntu会询问用户是否要显示,运行或在终端中运行...

脚本中是否有一种方法可以确定用户是否选择了"Run In Terminal"?

Gil*_*il' 6

严格地说,您无法判断用户在单击脚本后是否选择了"Run In Terminal",或者启动终端并从那里运行脚本.但是下面的命令应该对你有所帮助[ -t 2 ].

if [ -t 1 ]; then
  echo "Standard output is a terminal."
  echo "This means a terminal is available, and the user did not redirect the script's output."
fi
Run Code Online (Sandbox Code Playgroud)
if [ -t 2 ]; then
  echo "Standard error is a terminal." >&2
  echo "If you're going to display things for the user's attention, standard error is normally the way to go." >&2
fi
Run Code Online (Sandbox Code Playgroud)
if tty >/dev/null; then
  echo "Standard input is a terminal." >$(tty)
  echo "The tty command returns the name of the terminal device." >$(tty)
fi
Run Code Online (Sandbox Code Playgroud)
echo "This message is going to the terminal if there is one." >/dev/tty
echo "/dev/tty is a sort of alias for the active terminal." >/dev/tty
if [ $? -ne 0 ]; then
  : # Well, there wasn't one.
fi
Run Code Online (Sandbox Code Playgroud)
if [ -n "$DISPLAY" ]; then
  xmessage "A GUI is available."
fi
Run Code Online (Sandbox Code Playgroud)