简体   繁体   中英

how do I start a command in a terminal as if I'd opened the terminal and typed the command

I spend a lot of time opening terminals and typing commands in them.

$ gnome-terminal
(change mouse focus to new terminal)
$ reset && clear && tail -F ~/file_that_grows

every so often, I'll find myself going to that window and killing the process with control-C, and then restarting it. In fact I'll usually alias the reset && .... bit to something more typable, like rctf.

How can I automate the first bit of the process? The best I can do so far is

gnome-terminal --title rctf -e 'tail -F ~/.bashrc'

But there are various problems with this. Firstly the ~ doesn't get expanded, so the file isn't found. Secondly, when the command is over, the terminal exits.

Is there any way to automatically start a terminal exactly as if I'd opened it and then typed something? (Extra points if you can get the command in the history so that it can be restarted with up-arrow ).

For interactive programs, I use:

    xterm -e 'sh -c "vi $HOME/foo.txt; sh"'

The sh -c means that variables in my command string are substituted and the sh at the end means that a shell is started after I finish with vi instead of closing the terminal window.

For a non-interactive program like tail that can only be stopped by pressing CTRL-C to send SIGINT to the process, I use the shell trap built-in to be sure that a shell is run if the user presses CTRL-C instead of closing the terminal window:

    xterm -e sh -c 'trap sh SIGINT; tail -f $HOME/foo.txt'

If you don't mind storing your command in a file, you can abuse the --rcfile option in bash . For example, using the following script to store your command(s):

[me@home]$ cat $HOME/.term-rcfile  
. ~/.bashrc         # chain in the standard rc file
tail -F ~/.bashrc   # command to run

You can then do:

xterm -e "bash --rcfile $HOME/.term-rcfile -i"

Should also work for gnome-terminal:

gnome-terminal -e "bash --rcfile $HOME/.term-rcfile -i"

"(Extra points if you can get the command in the history so that it can be restarted with up-arrow )."

I can't see how to do that automatically, but if your run:

history -r ~/.term-rcfile

once you're in the new terminal (or whenever you want/need), entries from the file will be appended to your history (without running them) and you would then have access to them as you would normal history entries.

使用$ HOME变量而不是波形符。

gnome-terminal --title rctf -e "tail -F $HOME/.bashrc"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM