ubuntu 進階 ( 一 ) shell script 主講 : 廖凡磊 國立中央大學電算中心 ubuntu...
Post on 19-Dec-2015
276 views
TRANSCRIPT
Ubuntu 進階 ( 一 )shell script
主講 : 廖凡磊
國立中央大學電算中心ubuntu 短期訓練課程
agenda
Shell introduction & features
Shell script
Q & A
part1:shell introduction and features
為什麼要學習 shell 呢 ?
因為他好用 ... 廢話快速好用的組合命令分析系統記錄檔的利器一輩子受用的工具
What is SHELL
the hard protective outer case of an animal such as a snail, shellfish, or turtle(from Oxford)
shell is a piece of software that provides an interface for users. (from wikipedia)
橋樑 (from me)
登入 ubuntu 的流程
getty–get terminal(tty) (ctrl+alt+f1-f7)
login--authenticate the user
shell–provides an interface between user and kernel
logout-- good bye
程式執行流程
人下命令給 shell
shell 對 kernel 下命令kernel 對 hardware 執行工作,並回收結果kernel 回傳給 shell
shell 顯示出執行結果
kernel 又是什麼呢 ??
key: 其實 DOS 時代也有 shell, 就是 command.com
kernel
以人來比喻的話, shell 就像是語言
shell 也是一種 ap
各種硬體設備
/etc/shells
/bin/csh (c-like shell)
/bin/sh ( 目前由 dash 所取代 )
/bin/ksh (kornshell, by AT&T Bell LAB)
/bin/tcsh (enhanced csh, is FreeBSD default login shell)
/bin/bash (bourne-again shell, is ubuntu defaul login shell)
/bin/dash (debian almquist shell, 強調快速及檔案小 )
操作 1 :
看目前所使用的 shell 類型echo $SHELL
cat /etc/passwd/bin/false ??
換 shell
chsh
注意:請務必打完整的 shell 位置,不然會很麻煩
如何選擇自己要用的 shell
師法於你的朋友們愛用預設值BSD default shell ->csh/tcsh
Linux default shell -> sh/bash
學習哪一套 unix-like OS 也是一樣的
bash 的特色
Job control
Aliases
Shell functions
Directory stack
Command history
Command line editing
Vi Command line editing
Filename completion
設定你的 bash 環境
登入:/etc/profile -- 全域~/.bash_profile -- login 時用到~/.bash_login -- login 時用到~/.profile -- login 時用到 ~/.bashrc -- subshell 產生時會用到
登出:~/.bash_logout
實用的一些設定 in ~/.bashrc
grep 有顏色alias grep='grep --color'
man 有顏色 export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'
跟嗶嗶聲說不
tab 補齊時的嗶嗶聲in ~/.inputrc
set bell-style none # 關閉set bell-style visible # 開啟
vim 錯誤指令時的嗶嗶聲in ~/.vimrc
set vb ” 關閉
less 錯誤時的嗶嗶聲in ~/.bashrc
alias less='less -Q' # 關閉所有的錯誤報告
路徑問題
絕對路徑由 / 開始的路徑
相對路徑不是用 / 開始的路徑. # 當前的目錄.. # 上一層目錄~ # 家目錄 等於 /home/userName
tip:
寫 shell script 時最好是用絕對路徑如果查指令的絕對路徑
which command
指令複習
cd
mkdir
ls
ps
grep
who
rm
date
指令複習二
pwd
cp
mv
cat
less
bash 的基本認識
指令運用工作控制的運用輸入 , 輸出資料重導向管線的觀念與運用萬用字元的運用history 的設定與運用別名的設定與運用引號的觀念及運用變數的運用數值運算
指令的運用 (1)
單一指令pwd
ps -aux
netstat -an
連續指令mkdir ~/tempDir; cp ~/.* ~/tempDir; ls ~/tempDir
指令的運用 (2)
條件式指令grep google sampleCom.txt && more sampleCom.txt
grep google sampleCom.txt || echo “no”
gcc prog.c || echo ‘compile error’
&& -> it means than, 指令 1 失敗則不會執行後者 || ->it means else, 指令 1 成功則不會執行後者指令類別
內建命令 (built-in command)一般程式 (utility)如果辨別 : which command
指令運用 (3)
指令列的格式command option arguments
ls -al ~
rm -i test.txt
echo ”hello world”
遇到問題時man– 可靠的男人 ,man command
info command
option 中 加上 -h,--help
command-line editing
C-w 往前刪除一個字。M-f 往前一個字M-b 往後一個字C-u 刪除前面所有字元C-k 刪除後方所有字元C-l 清除螢幕C-r 往前搜尋指令 ( 非常好用 )
C-xC-e 可以使用 vim 寫入 script 讓他一次執行。
輸入 , 輸出重導向
> Output Redirection
>> Appending Output Redirection
< Input Redirection
<< keyword input redirection
輸入 , 輸出重導向 Ex.
Shell@ncucc> ls > ls.out
shell@ncucc> cat > text.out
Shell@ncucc> who >> ls.out
shell@ncucc> cat > text.out << eof
shell@ncucc> mail [email protected] << mailBody
管線的觀念與運用
command1 | command2
將指令 1 的結果當作指令 2 的輸入[user@ncucc]$cat /etc/passwd | grep false
[user@ncucc]$history | less
萬用字元的運用
*
可以代替任何字元?
可以代替一個字元[...]
可以代替中括號內的任何一個字元
萬用字元的運用 Ex
shell@ncucc> touch a.c; touch b.c;touch cc.c;mkdir dir1;mkdir dir2
shell@ncucc> ls *.c
a.c b.c cc.c
shell@ncucc> ls ?.c
a.c b.c
shell@ncucc> ls [ac]*
a.c b.c
shell@ncucc> ls [A-Za-z]*
history 的運用與設定
history
觀看歷史指令!!
執行上一個指令!n
執行第 n 個指令!string
搜尋以某字串 string 為開頭的過去並加以執行搜尋時以 event 數字大到小
!?string?
搜尋過去指令中有某個字串的指令
別名設定與運用
設定 alias name='command'
解除 unalias name
顯示全部設定 alias
顯示某個設定 alias name
可以在一開始就設定在 ~/.bashrc
alias 好用設定
alias name=command # 注意等號兩旁沒空格alias ls='ls -aF --color=always'
alias ll='ls -l'
alias search=grep
alias mcd='mount /mnt/cdrom'
alias ucd='umount /mnt/cdrom'
alias mc='mc -c'
alias ..='cd ..'
alias ...='cd ../..'
工作控制的運用
什麼是 job control
前景工作需等待提示符號出現才能進行下個動作
背景工作在一般的指令後面加個 &
常用的指令Ctrl+c 中斷指令Ctrl+z 放入背景,並暫停其指令bg %1 讓編號 1 的工作在背景執行fg %1 讓編號 1 的工作在前景執行
工作控制的運用 Ex.
vim hello.sh
Ctrl + z 放入背景fg 跳回去 vim 編輯介面
引數的觀念及運用
單引號 single quote(')
兩個單引號中的內容是不變的雙引號 double quote(”)
對自動替換雙引號中的特殊字元雙數
倒單引號 back quote(`)
會先被執行如果將倒單引號放在單引號中,會沒有作用
引號的觀念及運用 -- 範例
% color=red
% echo “$color”
red
% echo ‘$color’
$color
% echo “There are `who | wc -l` people online”
There are 1 people online
變數 (1)
印出變數的內容echo $HOME
echo $PATH
設值=
等號兩邊不能直接接空白字元;變數名稱只能是英文字母與數字,但是數字不能是開頭字元;
變數 (2)
鍵盤讀取變數read variable
read –p ” 提示字串 :” variable
echo $variable
陣列var[index]=content
echo ${var[index]}
變數 (3)
環境變數env
set
export
變數名稱HOME
SHELL
HISTSIZE
PATH
LANG
習題
如何利用 last 將你今天登入過的資訊印出來
如何讓檔案在刪除時會提醒是否真要刪除
如何秀出在 /bin底下任何以 a 為開頭的檔案檔名的詳細資料
解答
last | grep account
alias rm = ‘rm -i’
ls –al /bin/a*
數值運算
variable=$((1+2))
declare -i variable=6/2
let variable=1*2
整數範例
((i++)) 等於 let i++ 等於 i=$((i+1)) 等於 i=$(($i+1))
((C=A+B)) 等於 let C=A+B 等於 C=$((A+B)) 等於 C=$(($A+$B))
比爾蓋的 e化生活
蓋茲改裝他的豪宅,全面電子化,而且全部使用 Windows ,過不久他發現一些問題1. 每次回家,前門打開的時間要花費兩到三分鐘。2. 馬桶要沖水以前會詢問。「馬桶沖水會造成大便無法回收,您確定要沖馬桶嗎 ? 」3. 微波爐和烤箱在要快完成以前會突然跳開,面板顯示 : 「系統發生無法回復的錯 誤, 您要在試一遍嗎 ? 」4. 有時一些小東西突然不能使用的時候,如果試圖修復,會造成房子全倒需要整座房子重建。5. 如果你把窗戶全部打開,房子會突然停電,並且發出「系統資源不足,請您關閉一些窗戶。」6. 淋浴的時候熱水器會自動進入省電模式,需要甩兩下蓮蓬頭才會恢復供應熱水。7. 小偷闖入時,電視會自動打開,並且顯示整間房子的地圖。小偷可以按 HELP 鍵取得貴重物品放哪裡的資訊。8. 要使用電梯以前,必須先輸入用戶名稱及密碼然後聽電腦語音介紹如何使用電梯與逃生設備十分鐘。9. 所有買的新家具必須是 Microsoft 相容產品,否則會導致冰箱內物品遺失或烤麵包機烤焦麵包等的問題,嚴重時會造成房子倒塌。10. 蓋茲要跟老婆親熱的時候,床鋪語音會自動詢問:「這樣有得性病的危險性,是否要繼續 ? 」使用保險套時則會不斷要求:「已經有新款式,是否要更新 ? 」
part2:shell script
什麼是 shell script
script == 腳本,劇本批次檔 in dos
由很多指令集合而成的可執行文字檔
學習 shell script 的好處
自動化管理連續的指令單一化
用檔案把許多指令包在一起reuse
跨平台且學習歷程短
Editor(1)
Vim
預設的編輯軟體可大量存取文字檔擴充性強
Editor(2)
Nano
容易入門編輯提示
Hello Bash World
建立實習目錄
Shell@ncucc>>mkdir cctraining;cd cctraining
開檔Shell@ncucc>>nano first.sh
#!/bin/bash
#program:
# this is show “hello world”
#date:2007/10/16
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo “Hello Bash World!!”
離開 nano ctrl+x
Shell@ncucc>bash first.sh
解說
用什麼來寫 shell scriptvim
nano
gedit
註解# 以 # 開頭的文字不會被解譯
如何執行寫好的 shell script
chmod +x filename.sh;./filename.sh
bash filename.sh
good habit for write bash
多用註解#
headerscript 的功能;script 的版本資訊;script 的作者與聯絡方式;script 的版權宣告方式;script 的 History ( 歷史紀錄 );script 內較特殊的指令,使用絕對路徑的方式來下達;script 運作時需要的環境變數預先宣告與設定。
判斷式 (1)
用法test -e /home/ubuntu
test -e /etc/passwd && echo ”exist”|| echo ”not exist”
其他的測試選項-e 該『檔名』是否存在? ( 常用 )
-f 該『檔名』是否為檔案 (file)? ( 常用 )
-d 該『檔名』是否為目錄 (directory)? ( 常用 )
-eq 兩數值相等-gt n1 大於 n2 (greater than)
判斷式 (2)
判斷符號[]
[ -e /home/ubuntu ]
在中括號 [] 內的每個元件都需要有空白鍵來分隔;在中括號內的變數,最好都以雙引號來設定;在中括號內的常數,最好都以單或雙引號來設定
shell@ncucc> var1=”test1”
shell@ncucc>[ $var1 == ”test2” ] #error message
shell@ncucc>[ ”$var1” == ”test2” ] #accept
Positional Parameter
service ftp restart
$0 == service
$1 == ftp
$2 == restart
$# == 2
$@ == ftp restart
Positional Parameter Ex.
bash position_parameter.sh 3 2 1
[ -n “$1” ] – 判斷有沒有 $1這個變數&& 有則印出|| 沒有則結束此程式
if
第一型if [ 條件判斷式 ]; then
當條件判斷式成立時,可以進行的指令工作內容fi
第二型if [ 條件判斷式 ]; then
當條件判斷式成立時,可以進行的指令工作內容else
當條件判斷式不成立時,可以進行的指令工作內容fi
If (2)
第三型if [ 條件判斷式一 ]; then
當條件判斷式一成立時,可以進行的指令工作內容; elif [ 條件判斷式二 ]; then
當條件判斷式二成立時,可以進行的指令工作內容; else 當條件判斷式一與二均不成立時,可以進行的指令
工作內容; fi
利用 function 功能
功能模組化 加快速度Ubnutu預設的 function功能
Shell>declare -f
function fname() {
程式段}
Function Ex.
bash function.sh
Position parameter 的觀念也可以用在function 中
case
case $ 變數名稱 in
" 第一個變數內容 ")
程式段
;;
" 第二個變數內容 ")
程式段
;;
*)
不包含第一個變數內容與第二個變數內容的其他程式執行段
exit 1
;;
esac
case Ex.
bash case.sh one
注意結束的符號 ;;
區塊結束符號 esac
loop
while [ condition ] { && [ condition ]}
do
程式段落done
Loop Ex.
Bash while.sh
loop(2)
第一型for (( 初始值 ; 限制值 ; 執行步階 ))
do程式段done第二型
for i in word1 word2 word3; doecho $idone
Loop (2) Ex
bash for.sh
bash for2.sh
觀念整理
在 Linux 上可以找到哪些 shell( 舉出三個 ) ?那個檔案記錄可用的 shell ?而 Linux 預設的 shell 是?
1) /bin/bash, /bin/tcsh, /bin/csh2) /etc/shells3) bash ,亦即是 /bin/bash 。
在 shell 環境下,有個提示字元 (prompt) ,他可以修改嗎?要改什麼?預設的提示字元內容是?
可以修改的,改 PS1 這個變數,這個 PS1 變數的預設內容為:『 [\u@\h \W]\$ 』
如何顯示 HOME 這個環境變數? echo $HOME
如何得知目前的所有變數與環境變數的設定值? 環境變數用 env 而所有變數用 set 即可顯示
我是否可以設定一個變數名稱為 3myhome ? 不行!變數不能以數字做為開頭,參考變數設定規則的內容
在這樣的練習中『 A=B』且『 B=C』,若我下達『 unset $A』,則取消的變數是 A 還是 B?
被取消的是 B 喔,因為 unset $A 相當於 unset B 所以取消的是 B , A 會繼續存在!
如何取消變數與命令別名的內容? 使用 unset 及 unalias 即可 From linux.vbird.org
觀念整理
如何設定一個變數名稱為 name 內容為 It‘s my name ? name=It\'s\ my\ name 或 name="It's my name"
環境變數檔案的載入順序? 先由 /etc/passwd 取得 bash 這個 shell ,再到 /etc/profile 讀取主要的環境變數,同時亦會將 /etc/inputrc 及 /etc/profile.d 內容均讀入。之後,再到個人的家目錄讀取 ~/.bash_profile 及 ~/.bashrc 等檔案!
man page 的路徑設定檔案? /etc/man.config 或 /etc/man.conf
試說明 ‘ , “, 與 ` 這些符號在變數定義中的用途? 其中, " 可以具有變數的內容屬性, ' 則僅有一般字元,至於 ` 之內則是可先被執行的指令。
跳脫符號 \ 有什麼用途? 可以用來跳脫特殊字元,例如 Enter, $ 等等,使成為一般字元!
連續命令中, ;, &&, || 有何不同? 分號可以讓兩個 command 連續運作,不考慮 command1 的輸出狀態, && 則前一個指令必需要沒有錯誤訊息,亦即回傳值需為 0 則 command2 才會被執行, || 則與 && 相反!
如何將 last 的結果中,獨立出帳號,並且印出本月份曾經登入過的帳號? last | cut –d “ “ –f1 | sort | uniq
From linux.vbird.org
觀念整理
請問 foo1 && foo2 | foo3 > foo4 ,這個指令串當中, foo1/foo2/foo3/foo4 是指令還是檔案? 整串指令的意義為?
foo1/foo2 與 foo3 都是指令, foo4 是裝置或檔案。整串指令意義為:當 foo1 執行結果有錯誤時,則該指令串結束; 若 foo1 執行結果沒有錯誤時,則執行 foo2 | foo3 > foo4 ;foo2 將 stdout 輸出的結果傳給 foo3 處理; foo3 將來自 foo2 的 stdout 當成 stdin ,處理完後將資料流重新導向 foo4 這個裝置 /檔案
當我離開 bash 後,希望系統可以幫我將最近工作的:1.)工作日期; 2.)100 個歷史命令獨立 記錄到 ~/.bash_localcom 檔案中,該如何設定? 我可以編輯 ~/.bash_logout ,將這個檔案內容變成:# ~/.bash_logoutdate >> ~/.bash_localcomhistory 100 >> ~/.bash_localcomclear
From linux.vbird.org
參考資料
Getting Started with BASH 推薦http://www.hypexr.org/bash_tutorial.php
無名氏http://www.freebsd.org.hk/html/other/shell1.html
小信豬的原始部落格http://godleon.blogspot.com/2007/06/variable-shell-script-variable-object.html#sres
Writing shell scriptshttp://www.linuxcommand.org/writing_shell_scripts.php#contents
鳥哥的私房菜http://linux.vbird.org/
Q&A