# 表示註釋
#! 指定當前指令碼的解析器
#!/bin/bash
echo "Hello World"
; 命令分隔符
#!/bin/bash
echo hello;echo there
filename=ttt.sh
if [ -r "$filename" ]; then
echo "File $filename exists."; cp $filename $filename.bak
else
echo "File $filename not found."; touch $filename
fi; echo "File test complete"
;; 終止case選項
#!/bin/bash
varname=b
case "$varbname" in
[a-z]) echo "abc";;
[0-9]) echo "123";;
esac
. 等價與source命令。source命令用於在當前bash環境下讀取並執行filename.sh中的命令
$ source test.sh #等價於 . test.sh
" String將會阻止解釋Stirign中大部分特殊字元
' String將會阻止String中所有特殊字元的解釋,比"更強烈的方式
/ 檔名路徑分隔符,也可用作除法算術操作符
\ 一種單單字元的引用機制,\X會轉義成字元X
` 命令替換 command結構可以將命令的輸出賦值到另一個變數中去。``會優先執行
$ cp `mkdir bak` test.sh bak #先建立bak目錄,然後複製test.sh到bak中去
:空命令,相當於NOP(no option)。也被認為與shell的內建命令true作用相同。:是一個bash的內建命令,它的退出碼是0
#!/bin/bash
while :
do
echo "endless loop"
done
#!/bin/bash
condition=5
if [ $condition -gt 0 ]
then : #什麼都不做,退出分支
else
echo "$condition"
fi
:在與重定向操作符>結合使用時,將會把一個檔案清空,但不會修改這個檔案的許可權。若之前的檔案不存在,就建立這個檔案。
$ : > test.sh #test.sh被清空了
:在與重定向操作符>>結合使用時,將不會對預先存在的目標檔案產生任何影響,若這個檔案之前不存在,則建立這個檔案。
:還可以用來註釋行當不會關閉錯誤檢查,也可用來在/ect/passwd和$PATH變數中做分隔符。
? 在一個雙括號結構中,?就是C語言的三元操作符
#!/bin/bash
a=10
(( t=a<50?8:9 ))
echo $t
$變數替換、命令替換
$ cd $(echo Documents)
$ pwd
(())命令組:在括號中的命令列表,將會作為一個子shell來執行。在括號中的變數,由於是在子shell中所以對指令碼剩下的部分是不可用的。父程序,也就是指令碼本身,不能夠讀取在子程序中建立的變數,也就是在shell中建立的變數。
#!/bin/bash
a = 123
( a = 321; ) #括號中的變數a相當於一個區域性變數
echo "a = $a"
bash test.sh #output a = 123
(())還可以初始化陣列
#!/bin/bash
arr=(1 2 3 4 5 6) #不可以出現空格哦~ arr = ..是不行的哦
echo ${arr[3]}
{}檔名擴充套件
#!/bin/bash
if [ ! -w 't.txt' ];
then
touch t.txt
fi
echo 'test txt' >> t.txt
cp t.{txt,back}
{{}}也可代表程式碼快,又被稱為內部組,實際上是一個匿名函式。
#!/bin/bash
a=123
{ a=321; } #中間一定要有空格哦~
echo "a = $a"
$ bash test.sh #output a = 321 #在{}中宣告的變數,對於指令碼其它部分的程式碼來說是可見的
[]條件測試,[是shell內建test命令的一部分,並不是/urs/bin/test中的外部命令的一個連結
#!/bin/bash
a=5
if [ $a -lt 10 ]
then
echo " a : $a "
else
echo "a > 10"
fi
[]陣列元素,在一個array結構的上下文中,中括號用來引用陣列中的每個元素的編號。
#!/bin/bash
arr=(12 22 32)
arr[0]=2
echo ${arr[0]}
<>重定向
test.sh > filename #重定向test.sh的輸出到檔案filename中。若filename存在的話,那麼將會被覆蓋
test.sh &> filename #重定向test.sh的stdout和stderr到filename中
test.sh >&2 #重定向test.sh的stdout到stderr中
test.sh >> filename #把test.sh的輸出追加到檔案filename中。若filename不存在的話,將會被建立
| 管道,分析前邊命令的輸出,並將輸出作為後邊命令的輸入。
$ ps -ef | aux tomcat
-選項,字首,在所有的命令若想使用引數,前面都要加上-
#!/bin/bash
a=5
b=5
if [ "$a" -eq "$b" ]
then
echo " a is equal to b"
fi
-用於重定向stdin或stdou
備份最後24小時當前目錄下所有修改的檔案
#!/bin/bash
BACKUPFILE=backup-$(date +%m-%d-%Y) #在備份檔案中插入時間
archive=${1:-$BACKUPFILE}
tar cvf - `find . -mtime -1 -type f -print` > $archive.tar
gzip $archive.tar
echo "Directory $PWD backed up in archive file \"$archive.tar.gz\"."
exit 0
~表示home目錄