==========================================================
Shell script 定義函數以及傳遞參數
EXEC()
{
echo $1
}
#-------------
# Begine
#-------------
EXEC "Hello Shell world"
執行這段程序的結果是會在終端上打印出來:Hello Shell World.
參數列表可以用 $1, $2...來獲得。。
==========================================================
bash命令在shell腳本中的作用真的是舉足輕重啊,很有技巧的使用,可以解決很多實際問題
1. 統計包含的文件/目錄的個數
find ./ -maxdepth 1 -type d -print | wc -l
2. 解壓縮某個壓縮文件中的某個文件到指定文件夾
unzip -x one.zip onefile -d tmp_folder
3.顯示zip文件的內容
unzip -l one.zip
4. 去除文件中相同的行
sort -u filename.txt
5. 用sed awk 配合着正則表達式作文本內容提取,替換等等
6. 在給定的全路徑下獲取文件名
baesname /home/june/myfile.txt
* 配合和字符串替換的是用可以得到文件的路徑。
==========================================================
[3] 在shell中的字符串操作
1. 字符串替換
sed格式: sed -e 's/***/+++/flag'
use "***" replace "+++"
Eg:
sed -e 's/.*(/(.*/).java.*//1/p'
用項1去替換搜索到的整行,達到了從翻編譯過來的內容中找到類名
2. 批量替換字符串中的某個字符
格式: ${string//substr/instead_str}
Eg:
TEST="com.june.www"
TEST="${TEST//./_}"
echo $TEST
result: com_june_www
3. 取得字符串長度
${#string}
4. 字符串截取
- 從變量$string的結尾刪除最短匹配的substring
string="june say hello june"
after_str="${string%june}"
echo $after_str
results: june say hello
- 按照index截取
length=`expr ${#string}-1`
substr=${string: 0 : $length}
5. 字符串比較
ERROR_MSG=".* No such file"
check="rm -r folder"
len=`expr match "$check" "$ERROR_MSG"`
if [ $len -eq 0 ]; then
echo "Have"
else
echo "Not have"
fi
* 在這裏len可以獲取到匹配到的字符數量,如果等於零證明一點都不匹配,則文件存在
==========================================================
[4] 判斷文件目錄是否存在
1. tools="/home/user/tools"
if [ -e "$tools" ] 是否存在這個目錄
if [ ! -e "$tools" ] 是否不存在這個目錄
2. if [ -e "$tools/*.txt" ]
判斷這個目錄下是否存在txt文件
==========================================================
[5] shell的一些小技巧
1. Loop 文件夾中的文件
* for picture in "/home/pictues"
do
echo "The name of this picture is $picture"
done
* for song in `ls /home/songs/*.mp3`
2. 條件組合判斷
if [ "$June" = "Girl" ] || [ "$June" != "6" ]
3. 從終端讀入用戶輸入的信息
read variable
echo $variable
4. 在終端上打印帶顏色的字
echo -e "/033[31m ERROR: This is a red string!/033[0m"
# 31是所顯示顏色的代碼,40幾就是字體的背景
5. 將正在寫入的文件內容同步顯示到屏幕上,達到雙重定位輸出流的效果
touch tmp.txt
for i in 1, 2, 3
do
echo "Something" >> tmp.txt
tail -nl -f tmp.txt
done
6. 取變量中值的值
eg: A="June" B="A" 通過B取得A中存的值
eval tmp=/$$B
result: tmp 是 "June"
Shell腳本的總結基本完畢。。從零開始寫shell腳本還是挺有收穫的學習了很多的東西,尤其是對Linux命令的活用。。
這兩個星期在客戶的review我的refine下,我人生的第一個shell腳本已經順利交付。。人生中shell腳本的代碼行也超過了1000行。。呵呵