Bash shell history

Shell을 사용하다 보면 history 명령을 통해 이전 명령을 찾곤한다. 이 history 명령 buffer도 어느정도 늘려서 작업을 원할하게 할수도 있다.
그러나 history외에 Command line에서 좀 더 편한 기능을 사용하고 싶은 욕구가 있다.

 그럼 몇가지 case를 살펴봄으로 어떻게 사용할지 알아보자.

 

이전 명령 재실행

  1. 조금 전에 친 명령이 기억이 안난다. 뭐였지? 
    1. Arrow-UP/Arrow-Down: 이전/이후 명령
  2. 첫글자가 뭐로 시작했는지만 대충 기억이 난다.
    1. !String : String으로 시작하는 최근 history실행
      ex) !find : find vendor/google/framework/ -name *.sh
  3. 특정 단어만 기억이 난다. 
    1. !?Strng? : String을 포함하는 최근 history실행
  4. 기억이 정확히 안나 다른 명령이 실행될까 두려워 정확히 찾아서 하고 싶다.
    1. Ctrl +R : reverse search로 몇개의 keyword를 치면 이전명령에서 찾아준다.
    2. 아니면 그냥 history + grep
  • 사실 위에서 3번은 거의 못쓰겠다. 아무리 외어도 기억이 안난다. 가끔 이래서 linux가 싫다. 나 그냥 좀 골라쓰게 해줘라. 먼저 메뉴판 좀 보여줘?

 

이전 명령 재활용

  1. 바로 이전 명령의 명령이나 파라미터를 사용하고 싶다. 
    1. !:0, !:1, !:2, !:N, !:$ : 이전 명령어의 인자번호, 처음~ 마지막
    2. !^, !$, !* : 이전 명령의 인자중 첫번째, 마지막, 모두
  2. 바로 이전 명령의 앞 혹은 뒤에 뭘 붙여서 실행하고 싶다.
    1. !! String : 이전 명령 + 추가명령(String)
    2. String !! : 신규 명령(String) + 이전명령
  3. 바로 이전 명령을 변경해서 사용하고 싶다. 
    1. ^old^new^ : 이전명령 old를 new로 바꿔 실행
  4. 특정명령 번호(ex: !456)를 아는데, 조금 변경해서 사용하고 싶다. 
    1. !N:gs/old/new : N번째 이전명령을 old를 new로 모두 바꿔 실행

  • 위에서도 1-a, 3, 4번 다 못쓰겠다. 기억이 안나! 진짜되는지 난 이글 수정할때 다시 해본다. 이런 이런..

 

이런데, 나도 자주 기억이 안나 이중에 몇개만 사용하고 있다. 그런데, 특별히 반복작업을 할때 필요해서 찾아쓴다.
그럼 문제 나갑니다.

문제: build를 하였는데, sourcecode.obj파일이 어디에 생성되었는지 찾아보려고 find를 실행하였더니 이곳 저곳에 여러개가 생성되었다. 

  1. find로 찾은 파일에 대한 날짜 정보를 찾아 이중에 마지막으로 생성된 obj를 알아내려고 한다. 방법은 ?
  2. find로 찾은 파일을 모두 상위 dir(..)으로 copy하고 싶다. 방법은?

 

.---------------------------------------------------------------------------.
|                                                                           |
|                          Bash History Cheat Sheet                         |
|                                                                           |
'---------------------------------------------------------------------------'
| Peteris Krumins (peter@catonmat.net), 2008.02.15                          |
| http://www.catonmat.net  -  good coders code, great reuse                 |
|                                                                           |
| Released under the GNU Free Document License                              |
'---------------------------------------------------------------------------'
 ===================== Emacs Keyboard Shortcut Summary =====================
.--------------.------------------------------------------------------------.
|              |                                                            |
| Shortcut     | Description                                                |
|              |                                                            |
'--------------+------------------------------------------------------------'
| C-p          | Fetch the previous command from the history list.          |
'--------------+------------------------------------------------------------'
| C-n          | Fetch the next command from the history list.              |
'--------------+------------------------------------------------------------'
| M-<          | Move to the first line in the history.                     | 
'--------------+------------------------------------------------------------'
| M->          | Move to the end of the input history.                      |
'--------------+------------------------------------------------------------'
| C-r          | Search backward starting at the current line (incremental) |
'--------------+------------------------------------------------------------'
| C-s          | Search forward starting at the current line (incremental). |
'--------------+------------------------------------------------------------'
| M-p          | Search backward using non-incremental search.              |
'--------------+------------------------------------------------------------'
| M-n          | Search forward using non-incremental search                |
'--------------'------------------------------------------------------------'
 ======================= Vi Keyboard Shortcut Summary ======================
.--------------.------------------------------------------------------------.
|              |                                                            |
| Shortcut     | Description                                                |
|              |                                                            |
'--------------+------------------------------------------------------------'
| k            | Fetch the previous command from the history list.          |
'--------------+------------------------------------------------------------'
| j            | Fetch the next command from the history list.              |
'--------------+------------------------------------------------------------'
| /string or   | Search history backward for a command matching string.     |
| CTRL-r       |                                                            |
'--------------+------------------------------------------------------------'
| ?string or   | Search history forward for a command matching string.      |
| CTRL-s       | (Note that on most machines Ctrl-s STOPS the terminal      |
|              | output, change it with `stty' (Ctrl-q to resume)).         |
'--------------+------------------------------------------------------------'
| n            | Repeat search in the same direction as previous.           |
'--------------+------------------------------------------------------------'
| N            | Repeat search in the opposite direction as previous.       |
'--------------+------------------------------------------------------------'
| G            | Move to history line N (for example, 15G).                 |
'--------------'------------------------------------------------------------'
 ======================== History Expansion Summary ========================
 
 Event Designators:
.--------------.------------------------------------------------------------.
|              |                                                            |
| Designator   | Description                                                |
|              |                                                            |
'--------------+------------------------------------------------------------'
| !            | Start a history substitution.                              |
'--------------+------------------------------------------------------------'
| !!           | Refer to the last command.                                 |
'--------------+------------------------------------------------------------'
| !n           | Refer to the n-th command line (try `history' command).    |
'--------------+------------------------------------------------------------'
| !-n          | Refer to the current command line minus n.                 |
'--------------+------------------------------------------------------------'
| !string      | Refer to the most recent command starting with 'string'.   |
'--------------+------------------------------------------------------------'
| !?string?    | Refer to the most recent command containing 'string'.      |
'--------------+------------------------------------------------------------'
| ^str1^str2^  | Quick substitution. Repeat the last command, replacing     |
|              | 'str1' with 'str2'.                                        |
'--------------+------------------------------------------------------------'
| !#           | Refer to the entire command line typed so far.             |
'--------------'------------------------------------------------------------'
 Word Designators:
 (Word designators follow the event designators, separated by a collon ':')
.--------------.------------------------------------------------------------.
|              |                                                            |
| Designator   | Description                                                |
|              |                                                            |
'--------------+------------------------------------------------------------'
| 0            | The zeroth (first) word in a line (usually command name).  |
'--------------+------------------------------------------------------------'
| n            | The n-th word in a line.                                   |
'--------------+------------------------------------------------------------'
| ^            | The first argument (the second word) in a line.            |
'--------------+------------------------------------------------------------'
| $            | The last argument in a line.                               |
'--------------+------------------------------------------------------------'
| %            | The word matched by the most recent string search.         |
'--------------+------------------------------------------------------------'
| x-y          | A range of words from x to y (-y is synonymous with 0-y).  |
'--------------+------------------------------------------------------------'
| *            | All words but the zeroth (synonymous with 1-$).            |
'--------------+------------------------------------------------------------'
| x*           | Synonymous with x-$                                        |
'--------------+------------------------------------------------------------'
| x-           | The words from x to the second to last word.               |
'--------------'------------------------------------------------------------'
 Modifiers (modifiers follow word designators, separated by a colon):
.--------------.------------------------------------------------------------.
|              |                                                            |
| Modifier     | Description                                                |
|              |                                                            |
'--------------+------------------------------------------------------------'
| h            | Remove a trailing pathname component, leaving the head.    |
'--------------+------------------------------------------------------------'
| t            | Remove all leading pathname component, leaving the tail.   |
'--------------+------------------------------------------------------------'
| r            | Remove a trailing suffix of the form .xxx, leaving the     |
|              | basename.                                                  |
'--------------+------------------------------------------------------------'
| e            | Remove all but the trailing suffix.                        |
'--------------+------------------------------------------------------------'
| p            | Print the resulting command but do not execute it.         |
'--------------+------------------------------------------------------------'
| q            | Quotes the substituted words, escaping further             |
|              | substitutions.                                             |
'--------------+------------------------------------------------------------'
| x            | Quotes the substituted words, breaking them into words at  |
|              | blanks and newlines.                                       |
'--------------+------------------------------------------------------------'
| s/old/new/   | Substitutes 'new' for 'old'.                               |
'--------------+------------------------------------------------------------'
| &            | Repeats the previous substitution.                         |
'--------------+------------------------------------------------------------'
| g            | Causes s/old/new/ or & to be applied over the entire       |
|              | event line.                                                |
'--------------'------------------------------------------------------------'
 ============ History Behavior Modification via Shell Variables ============
.----------------.----------------------------------------------------------.
|                |                                                          |
| Shell Variable | Description                                              |
|                |                                                          |
'----------------+----------------------------------------------------------'
| HISTFILE       | Controls where the history file gets saved.              |
|                | Set to /dev/null not to save the history.                |
|                | Default: ~/.bash_history                                 |
'----------------+----------------------------------------------------------'
| HISTFILESIZE   | Controls how many history commands to keep in HISTFILE   |
|                | Default: 500                                             |
'----------------+----------------------------------------------------------'
| HISTSIZE       | Controls how many history commands to keep in the        |
|                | history list of current session.                         |
|                | Default: 500                                             |
'----------------+----------------------------------------------------------'
| HISTIGNORE     | Controls which commands to ignore and not save to the    |
|                | history list. The variable takes a list of               |
|                | colon separated values. Pattern & matches the previous   |
|                | history command.                                         |
'----------------'----------------------------------------------------------'
 ============ History Behavior Modification via `shopt' Command ============
.----------------.----------------------------------------------------------.
|                |                                                          |
| shopt Option   | Description                                              |
|                |                                                          |
'----------------+----------------------------------------------------------'
| histappend     | Setting the variable appends current session history to  |
|                | HISTFILE. Unsetting overwrites the file each time.       |
'----------------+----------------------------------------------------------'
| histreedit     | If set, puts a failed history substitution back on the   |
|                | command line for re-editing.                             |
'----------------+----------------------------------------------------------'
| histverify     | If set, puts the command to be executed after a          |
|                | substitution on command line as if you had typed it.     |
'----------------'----------------------------------------------------------'
 shopt options can be set by a `shopt -s option' and
 can be unset by             a `shopt -u option'.
 =============================== Examples ==================================
 $ echo a b c d e    (executes `echo ab c d e`)
 a b c d e
 $ echo !!:3-$       (executes `echo c d e`)
 c d e
 $ echo !-2:*:q      (executes `echo 'a b c d e'`)
 a b c d e
 $ echo !-3:1:2:4:x  (executes `echo 'a' 'b' 'd'`)
 a b d
 $ echo !-4:1-3:s/a/foo/:s/b/bar/:s/c/baz/ (executes `echo foo bar baz`)
 foo bar baz
 $ tar -xzf package-x.y.z.tgz
 ...
 $ cd !-1:$:r        (executes `cd package-x.y.z`)
 package-x.y.z $
 
 $ ls -a /tmp
 file1  file2  file3 ...
 $ ^-a^-l^           (executes `ls -l /tmp`)
 -rw-------  1  user  user  file1
 ...
 ===========================================================================
.---------------------------------------------------------------------------.
| Peteris Krumins (peter@catonmat.net), 2008.02.15                          |
| http://www.catonmat.net  -  good coders code, great reuse                 | 
|                                                                           |
| Released under the GNU Free Document License                              |
'---------------------------------------------------------------------------'