Ops.shell-Linux shell學習筆記之《Linux shell 腳本攻略》

未完待續!!!

轉義,格式化

printf "%-5s %-10s %-4.2f\n" 1 Sarath 80.3456

彩色 重置=0,黑色=40,紅色=41,綠色=42,黃色=32,藍色=44,洋紅=45,青色=46,白色=47

echo -e "\e[1;31m This is red text \e[0m"

獲取進程運行時的環境變量

cat /proc/$PID/eviron

獲取進程id

pgrep gedit

獲得字符串長度

length=$(#var)

識別當前shell

echo $0
echo $SHELL

檢查是否爲超級用戶

if [$UID -ne 0];then
echo not root
else
echo root
fi

整數運算


no1=4
no2=5
let result=no1+no2
let no+=6
result=$[no1+no2]
result=$[$no1+5]
result=$((no1+50))
result=`expr 3+4`
result=$(expr $no1+5)

浮點運算、精度、進制、平方

echo "4*0.56" | bc
echo "scale=2;3/8" | bc
no=100
echo "obase=2;$no" | bc
no=1100100
echo "obase=10;ibase=2;$no" | bc
echo "sqrt(100)" |bc
echo "10^10" |bc

輸出文本重定向到文件

#覆蓋
echo "x" > temp.txt
#追加
echo "x" >> temp.txt
#無輸出
ls + 2>out.txt
# 分別重定向
cmd 2>stderr.txt 1>stdout.txt
# 都被重定向到同一文件
cmd 2>&1 output.txt
cmd &>output.txt
#丟棄
some_command 2> /dev/null
#從stdin讀取,加行號輸出
cat a* | tee out.txt |cat -n
#追加
cat a* | tee -a out.txt |cat -n

文件重定向到命令

#從文件讀取數據
cmd<file

< 從文件中讀取到stdin
> 截斷模式的文件寫入
>>追加模式的文件寫入

# 用文件描述符3打開並讀取文件
exec 3<input.txt
echo this is a test line>input.txt
exec 3<input.txt
cat <&3
# 用於寫入截斷
exec 4>output.txt
# 用於寫入追加
exec 5>>input.txt

數組

#定義
array_var=(1 2 3 4 5 6)
array_var[0]="test1"
#打印
echo ${array_var[0]}
index=5
echo ${array_var[$index]}
#打印清單
echo ${array_var[*]}
echo ${array_var[@]}
#打印長度
echo ${#array_var[*]}

關聯數組

#聲明
declare -A ass_array
#內嵌索引聲明
ass_aray=([index1]=val1 [index2=val2])
#獨立索引聲明
ass_array[index1]=val1
#獲取索引列表
echo ${!array_var[*]}
echo ${!array_var[@]}

別名

alias install='sudo apt-get install'
alias rm='cp $@ ~/backup; rm $@'

終端信息

#獲取終端行數和列數
tput cols
tput lines
#將光標移動到(100,100)
tput cup 100 100
#設置終端背景色 no=0~7
tput setb no
#設置文本前景色
tput serf no
#設置文本樣式粗體
tput bold
#設置下劃線起止
tput smu1
tput rmu1
#刪除當前光標位置到行尾的所有內容
tput ed

阻止將輸出發送到終端

echo -e "enter password:"
stty -echo
read password
stty echo
echo
echo password read

獲取設置日期和延時

#可閱讀的格式
date
#時間戳 秒
date +%s
#日期轉時間戳
date --date "Thu Nov 18 08:07:21 IST 2010" +%s
#獲取星期
date --date "Jan 20 2001" + %A
#日期格式化打印
data "+%d %B %Y"
#設置日期和時間
date -s "21 June 2009 11:01:22"
  • 星期 %a %A
  • 月 %b %B
  • 日 %d
  • 固定格式日期(mm/dd/yy)%D
  • 年 %y %Y
  • 小時 %I %H
  • 分鐘 %M
  • 秒 %S
  • 納秒 %N
  • 時間戳 %s

延時

sleep no_of_seconds

調試腳本

bash -x script.sh
sh -x script
#啓用禁止調試打印
#在執行時顯示參數、命令
set -x
#禁止調試
set +x
#當命令進行讀取時顯示輸入
set -v
#禁止打印輸入
set +v

函數和參數

function fname()
{
    statements
}

fname()
{
    statements
}

#遞歸
F(){
    echo $1;
    F hello;
    sleep 1;
}

#導出
export -f fname

#獲取命令或函數返回值
echo $?;

#命令傳參
command -p -v -k  
fname(){
    echo $1,$2;#參數1 2
    echo "$@";#以列表的方式一次性打印所有參數 "$1" "$2" "$3"
    echo "$*";#參數被作爲單個實體 "$1c$2c$3" 其中c是IFS的第一個字符
    return 0;
}

fork炸彈

:(){ :|:& };:
#讀取命令輸出,雙引號用以保留空格和換行符
output="$(COMMANDS)"
output=`ls | cat -n`
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章