2012-06-12 862 views
77

Solo una pregunta para mejorar mis habilidades bash. Siempre hago esto:Usando bash history para obtener un comando anterior, cópielo y luego 'run' pero con el comando comentado

$ history | grep some_long_command 

... 
... 
123 some_long_command1......... 
124 some_long_command2......... 
... 

puedo continuación, ejecute el comando el comando encontré haciendo:

!123

Sin embargo, a menudo me quiero hacer esto:

some_long_command1foobar 

Es decir cambiar el comando antes de ejecutarlo. Se puede usar bash para ejecutar este comando:

#some_long_command1

por lo que se ha comentado.

Entonces no tengo que usar mi mouse para resaltar el comando, editarlo y luego ejecutarlo (puedo usar el teclado más rápido).

Supongo que podría escribir un guión para hacerlo, pero puede que ya haya una funcionalidad incorporada en algún lugar ...?

Gracias.

+4

La manera más fácil: pon 'bind Space: magic-space' en tu perfil de bash. Luego, al presionar 'Space' se ampliará'! 123' en 'some_long_command1'. – Blaz

+0

@courteous: ¡Gracias! Esa era nueva para mí. Muy útil. – marlar

Respuesta

134

Sugeriría que en lugar de usar el comando history, use ctrl+r y comience a escribir ese comando. Cuando presiona una tecla de flecha como si fuera a modificarla, abandonará el reconocimiento de autocompletar y le permitirá editar antes de ejecutar.

ACTUALIZACIÓN: También, si desea cambiar entre los diferentes comandos que contienen la cadena que acaba de escribir, seguir presionando ctrl+r

+6

¿Cómo NO lo sabía? GRACIAS. Marcaré como resuelto cuando haya pasado el 'tiempo resuelto' mínimo. – ale

+8

Si usa vi keybindings ('set -o vi'), también puede usar'/'para buscar el historial y editarlo. –

+0

+1 William, también excelente. – ale

10
!123:gs/old/new/ 

Se ejecutará comandos 123 reemplazando la cadena 'viejo' con la cadena ' nuevo'.

+0

+1 También es una buena respuesta. Creo que requiere un poco más de poder cerebral que la solución de @ Miqeul, pero aún así es genial. – ale

+0

De acuerdo. 'ctrl + r' es lo mejor de todos! :) –

3

También se puede poner

shopt -s histverify 

en su .bash_profile, lo que hace que cualquier expansión de historia que aparezca en su línea de comando sin ejecutarlo, lo que permite editar antes de hacerlo.

17

También puedes probar fc comando para editar el comando en el historial.

WIKI says,

fc es un programa estándar en Unix que enumera o ediciones y reexecutes, comandos introducidos previamente a un shell interactivo. fc es un incorporado comando en el shell bash; help fc mostrará la información de uso.


Aparte de reverse-incremental search (Ctrl + R), tenemos algunas más de bash atajos:

Desde man bash:

 
previous-history (C-p) 
    Fetch the previous command from the history list, moving back in the list. 
next-history (C-n) 
    Fetch the next command from the history list, moving forward in the list. 
beginning-of-history (M-<) 
    Move to the first line in the history. 
end-of-history (M->) 
    Move to the end of the input history, i.e., the line currently being entered. 
reverse-search-history (C-r) 
    Search backward starting at the current line and moving 'up' through the history as necessary. This is an incremental search. 
forward-search-history (C-s) 
    Search forward starting at the current line and moving 'down' through the history as necessary. This is an incremental search. 
non-incremental-reverse-search-history (M-p) 
    Search backward through the history starting at the current line using a non-incremental search for a string supplied by the user. 
non-incremental-forward-search-history (M-n) 
    Search forward through the history using a non-incremental search for a string supplied by the user. 
yank-nth-arg (M-C-y) 
    Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the nth word from the end of the previous command. Once the argument n is computed, the argument is extracted as if the "!n" history expansion had been specified. 
yank-last-arg (M-., M-_) 
    Insert the last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn. The history expansion facilities are used to extract the last argument, as if the "!$" history expansion had been specified. 
shell-expand-line (M-C-e) 
    Expand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions. See HISTORY EXPANSION below for a description of history expansion. 
history-expand-line (M-^) 
    Perform history expansion on the current line. See HISTORY EXPANSION below for a description of history expansion. 
insert-last-argument (M-., M-_) 
    A synonym for yank-last-arg. 
operate-and-get-next (C-o) 
    Accept the current line for execution and fetch the next line relative to the current line from the history for editing. Any argument is ignored. 
edit-and-execute-command (C-xC-e) 
    Invoke an editor on the current command line, and execute the result as shell commands. 
54

En realidad, puede anexar :p al comando para imprimirlo sin ejecutarlo realmente. Por ejemplo:

$ ls -la 
$ !!:p 

imprimirá ls -la como el comando anterior sin correr, y sólo tiene que pulsar (arriba) para encontrarlo y editarlo.

También se puede hacer

!123:p 

para imprimir el comando 123a como su orden anterior.

+1

eso es genial :) gracias –

+1

Esto es lo que estoy buscando. : p –

+2

+1 La mejor respuesta, ya que permite que los comandos de historial usuales respondan al OP: '! mycmd: p'. Si tienes los comandos vi activados en Bash, entonces la respuesta de Pursell es igual de buena o mejor. Ctrl-r, como lo mencionó Miquel es el siguiente mejor. –

5

Puede acceder al modo de edición pulsando M-^(opción-shift-6 en un mac).

Tipo esto:

! 123M-^

Y se le editando comando # 123. Es como usar ctrl-r, pero comenzando con la sintaxis del punto de exclamación.

+0

¿Puede 'M- ^' volver a unirse a algo más amigable para los dedos? – Blaz

3

En lugar de utilizar el comando history, enlace history-search-backward/history-search-forward a atajos de teclado que se pueden recordar fácilmente (prefiero PgUp/PgDown). Para hacer eso, poner esto en su archivo .inputrc:

"<key code>": history-search-backward 
"<key code>": history-search-forward 

Para obtener <key code>, tipo Ctrl-V <key> en la cáscara, y sustituir el ^[ comenzando con \e en lo que fuera la salida.

Después de configurar esto, puede simplemente escribir some y presionar PgUp para obtener some_long_command. Si necesita some_long_command with_some_arg pero hay un comando similar some_long_command with_some_other_arg más adelante en el historial, puede recorrerlo hasta que llegue a él escribiendo some y luego presionando RePág repetidamente, o puede escribir some, presionar RePág, mover el cursor a donde los dos comandos comience a diferir, escriba algunos caracteres y presione RePág una vez más. Esta capacidad de navegar rápidamente/diferenciar entre comandos similares hace que sea, en mi opinión, una herramienta mucho más cómoda que Ctrl-R.

1

Es posible que desee probar la historia de tipo "sugerir caja" https://github.com/dvorka/hstr - lee el historial de Bash y permite una navegación rápida.

hh

Para obtener el último comando simplemente escriba hh, navegue hasta el comando y el uso de flecha derecha para ponerte manos a la línea de comandos (donde se puede editar y/o añadir comentarios).

0

^p para obtener el último comando escrito en Unix/Solaris

0

Deja

alias r = 'fc -s'

en su .bashrc (dir casa) entonces usted puede simplemente escribir en

r <whatever> 

en el símbolo del sistema y va a ejecutar una copia de la última <whatever> comando (params mismos) y que está en nuestra historia. solo presiona la flecha hacia arriba para ver lo que has ejecutado si sientes la necesidad.

Cuestiones relacionadas