2014年8月25日 星期一

bash script 學習隨筆

最近在學習shell script這個系統管理的利器,簡單記錄幾個常用語法

script的執行



  • 透過 sh 執行 => bash分支出子進程執行script
  • 透過 source 執行 => 父進程執行script, 若script內有exit 0之類的,bash shell會被關掉

變數設定規則


  • 變數與內容用等號聯結,中間不能加上空格
  • 若該變數希望在別的子程序執行時仍存在,用export VAR
  • 取消變數設定用 unset VAR

用日期設定檔名



#!/bin/bash
#Program:
#    Normally we'll add some comment of the script here
#History:
#    2014/08/26    Andy    First release
#Contact info:

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
#先定義一些常用的參數宣告

read -p "input something: " something
echo -e "get $something"
#get input

filename=${something:-"defaultname"}

date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date +%Y%m%d)
#用$(command)或` command `來透過指令取得參數

file1=$filename$date1
file2=$filename$date2

touch $file1
touch $file2

exit 0
#if you do echo $? after executed the script, you'll get the return value of 0 printed

shell script中的運算


$((運算))

ex. echo $((13 % 3))
若寫成 $(13 % 3) bash會試著去執行'13'這支程式而出現error message

script中的判斷


test 是個很好的工具

awk的應用



awk -F 的應用:
word=10.00
word=$(echo $word | awk -F'.' '{print $0}')    => 10.00
word=$(echo $word | awk -F'.' '{print $1}')    => 10
word=$(echo $word | awk -F'.' '{print $2}')    => 00




沒有留言:

張貼留言