如何使用已在命令行上输入的某些文本启动终端?

emf*_*emf 28 command-line bash scripts gnome-terminal

与其重新表述我的问题,不如让我向您描述所需的用户案例:

我创建了一个简短的 shell 脚本来运行命令“gnome-terminal --someoptionflagname '我要发布的文本'”,并执行这个脚本。

弹出 Gnome 终端,命令行提示后跟我的文本。

IE: fields@mycomputer:/$ my text to be posted

这能做到吗?

ænd*_*rük 33

您可以使用expect ( install )执行此操作。创建并制作可执行文件~/bin/myprompt

#!/usr/bin/expect -f

# Get a Bash shell
spawn -noecho bash

# Wait for a prompt
expect "$ "

# Type something
send "my text to be posted"

# Hand over control to the user
interact

exit
Run Code Online (Sandbox Code Playgroud)

并使用以下命令运行 Gnome 终端:

gnome-terminal -e ~/bin/myprompt
Run Code Online (Sandbox Code Playgroud)


Gor*_*ght 9

ændrük 的建议非常好,对我有用,但是该命令是在脚本中硬编码的,如果您调整终端窗口的大小,它就无法正常工作。使用他的代码作为基础,我添加了将命令作为参数发送给 myprompt 脚本的功能,并且该脚本正确处理了终端窗口大小的调整。

#!/usr/bin/expect

#trap sigwinch and pass it to the child we spawned
#this allows the gnome-terminal window to be resized
trap {
 set rows [stty rows]
 set cols [stty columns]
 stty rows $rows columns $cols < $spawn_out(slave,name)
} WINCH

set arg1 [lindex $argv 0]

# Get a Bash shell
spawn -noecho bash

# Wait for a prompt
expect "$ "

# Type something
send $arg1

# Hand over control to the user
interact

exit
Run Code Online (Sandbox Code Playgroud)

并使用以下命令运行 Gnome 终端:

gnome-terminal -e "~/bin/myprompt \"my text to be posted\""
Run Code Online (Sandbox Code Playgroud)


Gil*_*il' 8

如果我理解正确,您希望您的第一个输入行预先填充到您在 gnome-terminal 命令行上传递的内容。

我不知道如何用 bash 做到这一点,但这里有一些接近的东西。在您的 中~/.bashrc,在最后添加以下行:

history -s "$BASH_INITIAL_COMMAND"
Run Code Online (Sandbox Code Playgroud)

运行gnome-terminal -x env BASH_INITIAL_COMMAND='my text to be posted' bash,然后Up在提示处按以调用文本。

另请注意,如果您set -o history在 . 末尾添加后跟注释.bashrc,它们将在 bash 启动时输入到历史记录中,因此您可以将它们用作编辑的基础,方法是使用Up键到达它们并删除初始的#.

  • 虽然不是我正在寻找的解决方案,但这本身就很有趣。 (2认同)