bash shell tips

介紹:

 

用 Linux 的人大多數時間都是和 shell 打交道,

日復日, 年復年, 漸漸可能有點累 .......

如果你有這感覺, 那相信你仍未獲得用 shell 的奧義 ~

以下只是拋磚引玉, 還有很多技巧留待大家發掘 ^ ^

 

目錄:

  1. insert-completions ( Alt + * )
  2. 返回值 ( $? )
  3. 上一指今的參數 ( !* )
  4. bash_completion ( 指令的參數 )
  5. history 怎麼會沒有時間 ??
  6. bash 的設定 ( set -o )

 

 


 

insert-completions

 

假設現在有一個目錄, 內有 file_1, file_2, file_3 ........... file_10

而你想刪除 1-5, 8-10 , 但保留 6, 7

那你有兩個方法

 

1: 一般做法

臨時移走 file_6, file_7 , 然後在目錄內執行 rm * , 之後才把檔案搬回來

( 在 bash shell 上, * 代表了所有檔案 )

2: 巧妙的方式

那你可以輸入 rm 然後按 alt + *

那你會見到

rm file_1, file_2, file_3 ........... file_10

之後以 ctrl + w 刪除不要的項目然後按 Enter ^ ^

 


 

返回值 ( $? )

 

在 linux 上有一個特殊的環境變量 $?

他用來表達之前指令的返回值

echo $?            # 查看此值

當此值非 0 時, 那代表先前的指令不執行失敗,

而返回值即是 "錯誤代碼"

 


 

上一指今的參數 ( !* )

 

!* 保存著上一條命令的所有參數

應用 :

head docfile

vi !*

 

 


 

bash-completion

 

apt-get install bash-completion

/etc/bash_completion
/etc/bash_completion.d/

==========================================

~/.bash_profile

if [ -f /etc/bash_completion ]; then
 . /etc/bash_completion
fi

===========================================

apt-get

and then press the TAB key once and the command will be completed to apt-get. Or issue this:

autoclean        check            dselect-upgrade  remove           upgrade
autoremove       clean            install          source
build-dep        dist-upgrade     purge            update

apt-get upd

and then press the TAB key once and the command will be completed to

apt-get update

==========================================

When the bash_completion file is sourced (or loaded)
everything inside the /etc/bash_completion.d directory is also loaded.

 

==========================================

一點意外:

/etc/bash_completion: line 273: syntax error near unexpected token `<'
/etc/bash_completion: line 273: `      done < <( compgen -d -- "$(quote_readline "$cur")" )'

It happens because you're calling bash as /bin/sh, instead of /bin/bash.

 

Alt + /

 

 


 

history 怎麼會沒有時間
 

如果只知事情發生過, 而不知幾時發生, 那實在有點缺憾 ..........

但只要巧妙的一句

export HISTTIMEFORMAT="%F %T "

原來的

  494  l
  495  mkdir desktop
  496  cd desktop/
  497  apt-get update; apt-get upgrade
  498  top
  499  ifconfig
  500  route -n
  501  history
 

變成

  495  2009-05-03 17:56:03 mkdir desktop
  496  2009-05-03 17:56:03 cd desktop/
  497  2009-05-03 17:56:03 apt-get update; apt-get upgrade
  498  2009-05-03 17:56:03 top
  499  2009-05-03 17:56:03 ifconfig
  500  2009-05-03 17:56:03 route -n
  501  2009-05-03 17:56:06 history
  502  2009-05-03 17:56:42 export HISTTIMEFORMAT="%F %T "
  503  2009-05-03 17:56:46 history
 

幾時做過什麼現在就一目暸然

 


 

bash 的設定 ( set -o )

 


 

 


 

 

 


 

 

Creative Commons license icon Creative Commons license icon