如何在不执行命令的情况下从Shell脚本在命令提示符下输入文本? [英] How to enter text at command prompt from shell script without executing command?
问题描述
有没有办法在命令提示符没有发出命令的情况下使shell脚本输出文本?
Is there a way to have a shell script output text at the command prompt WITHOUT issuing the command?
上下文:我每天几次通过SSH登录到一台特定的计算机中,大约80%的时间,我一登录就输入相同的三个命令.我只是将这些命令放在我的 .bashrc
中,但是20%的时间我不要发布这些命令.我想知道是否可以在 .bashrc
中放入一些命令,该命令会自动在命令行中放置一个字符串,以便在我登录时看到:
CONTEXT: I SSH into a particular machine several times a day, and about 80% of the time, I type the same three commands as soon as I login. I would just put these commands in my .bashrc
, but 20% of the time, I do NOT want to issue these commands. I'm wondering if there is some command I can put in .bashrc
that will automatically put a string at my command line, so that when I login I see:
$ cd some/dir && ./some_script.sh
然后我可以仅在80%的时间内按下Enter键,或者在其他20%的时间内仅清除文本.
I could then just press enter 80% of the time or just clear the text the other 20% of the time.
推荐答案
(受 Abdul Rehman的答案的启发.)
将其作为 .bashrc
文件中的 last 行:
read -e -p "(Control-C to cancel) $ " -i "cd some/dir && ./some_script.sh" && eval "$REPLY"
-
read -e
使您可以使用Readline输入字符串进行编辑. -
-p
为该一次性命令提供了伪提示. -
-i
提供了一个默认字符串,您可以编辑或按Enter接受它. read -e
lets you enter a string using Readline for editing.- The
-p
provides a pseudo-prompt for this one-time command. - The
-i
provides a default string which you can edit or hit Enter to accept.
如果您按Enter键,则 read
会设置 REPLY
的值,并以状态0退出,从而导致执行以下 eval
.(通常, eval
不是一个好命令;但是,在这里,无论如何您都将看到一个交互式外壳,因此这里没有太大的风险.)如果键入 Control - C 代替, read
以状态1退出,并且以下 eval
不执行,使您进入命令提示符.
If you hit Enter, read
sets the value of REPLY
and exits with status 0, causing the following eval
to execute. (Usually, eval
is not a good command to use; however, here you would be presented with an interactive shell anyway, so there's not much risk here.) If you type Control-C instead, read
exits with status 1 and the following eval
is not executed, leaving you at your command prompt.
这篇关于如何在不执行命令的情况下从Shell脚本在命令提示符下输入文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!