Bash: 在新终端中执行带有参数的命令

Bash: Execute command WITH ARGUMENTS in new terminal

所以我想在 bash 中打开一个新终端并执行带参数的命令。 只要我只将 ls 之类的命令作为命令,它就可以正常工作,但是当我将 route -n 之类的命令作为带参数的命令时,它就不起作用。 代码:

gnome-terminal --window-with-profile=Bash -e whoami#作品

gnome-terminal --window-with-profile=Bash -e route -n #不起作用

我已经尝试在命令周围加上“”等等,但它仍然不起作用

试试这个:

gnome-terminal --window-with-profile=Bash -e 'bash -c "route -n; read"'

最后的 read 防止 window 在执行前面的命令后关闭。当你按下一个键时它会关闭。

如果你想体验头痛,你可以试试多引用嵌套:

gnome-terminal --window-with-profile=Bash \
  -e 'bash -c "route -n; read -p '"'Press a key...'"'"'

(在以下示例中没有最终的 read。假设我们在配置文件中修复了它。)

如果你想打印一个空行并享受多级转义:

gnome-terminal --window-with-profile=Bash \
  -e 'bash -c "printf \\n; route -n"'

同理,另一种引用方式:

gnome-terminal --window-with-profile=Bash \
  -e 'bash -c '\''printf "\n"; route -n'\'

变量用双引号展开,而不是单引号,所以如果你想展开它们,你需要确保最外面的引号是双引号:

command='printf "\n"; route -n'
gnome-terminal --window-with-profile=Bash \
  -e "bash -c '$command'"

引用可能会变得非常复杂。当你需要比简单的命令更高级的东西时,建议编写一个独立的 shell 脚本,其中包含你需要的所有可读的参数化代码,将其保存在某个地方,比如 /home/user/bin/mycommand,然后调用它只是

gnome-terminal --window-with-profile=Bash -e /home/user/bin/mycommand

您可以使用以下命令启动新终端:

gnome-terminal --window-with-profile=Bash -- \
    bash -c "<command>"

要继续使用正常的 bash 配置文件,请添加 exec bash:

gnome-terminal --window-with-profile=Bash -- \
    bash -c "<command>; exec bash"

以下是创建 Here document 并将其作为命令传递的方法:

cmd="$(printf '%s\n' 'wc -w <<-EOF
  First line of Here document.
  Second line.
  The output of this command will be '15'.
EOF' 'exec bash')"

xterm -e bash -c "${cmd}"

要打开一个新终端和 运行 使用脚本的初始命令,请在脚本中添加以下内容:

nohup xterm -e bash -c "$(printf '%s\nexec bash' "$*")" &>/dev/null &

当引用 $* 时,它将参数扩展为单个单词,每个参数由 IFS 的第一个字符分隔。 nohup&>/dev/null &仅用于让终端在后台运行。