How to start bash and immediately "type" command into it?
I want bash to first execute a command, but after the command finishes (or Ctrl+C'ed) go into interactive mode (preferrably with the command in history, available for up).
How to attain it in easiest and the most beautiful way?
Inspired by cmd.exe's /K
:
$ wineconsole cmd.exe /K echo qqq
qqq
Z:\home\wine>
Cleaner version of the Scott's answer:
-
Put this to
.bash_profile
:if [ ! -z "$EXECUTE_COMMAND" ]; then history -s "$EXECUTE_COMMAND" $EXECUTE_COMMAND fi
-
Start bash this way:
$ EXECUTE_COMMAND='ping 127.0.0.1' bash -l PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_req=1 ttl=64 time=0.177 ms ... ^C 5 packets transmitted, 5 received, 0% packet loss, time 3996ms $ $ ping 127.0.0.1
I’m not 100% sure that I understand exactly what you’re asking for, and (alas) I don’t have access to a system with bash
on it at the moment, but maybe the following will help you. Put this at the end of your .bashrc
:
if [ -f ~/.bash_initial_command ] then . ~/.bash_initial_command rm ~/.bash_initial_command fi
(where .bash_initial_command
is an arbitrary filename; pick a different one if you want), and then write a script that does this:
(echo "history –s '$@'"; echo "$@") > ~/.bash_initial_command
I.e., this puts the command (that is presented to the above script as argument(s)) in a place where the next interactive bash
to start will find it and execute it. (E.g., if you run set_up_cmd ls –l
, then your next bash
will run ls –l
.) history –s
puts a command into history without executing it.
Note: I do not know whether this will work from .bashrc
.
This will need more refinement if you will want to use commands with quotes (i.e., quoted special characters) or redirection (<
or >
); or compound commands (i.e., containing ;
, |
, &&
, or ||
).
A minor problem: if you Ctrl+C the command, that will probably terminate the .bashrc
processing and thereby prevent the .bash_initial_command
file from being deleted. You can probably handle that by doing
if [ -f ~/.bash_initial_command ] then mv ~/.bash_initial_command ~/.bash_initial_command.$$ trap "rm -f ~/.bash_initial_command.$$" 0 . ~/.bash_initial_command.$$ rm -f ~/.bash_initial_command.$$ fi
This gives .bash_initial_command
a unique name, so as to avoid collisions, and arranges that it will be deleted when the shell exits.
If you need to be able to fire up several of these simultaneously, consider building the “tty” name $(basename $(tty))
into the .bash_initial_command
filename.
Of course, doing this makes it all the more important to be sure that your home directory is not writable by anybody but yourself.