hello world
#! /bin/bash 聲明為bash執(zhí)行
#!/bin/bash
# This is a very simple example
echo Hello World
變量
bash的變量無(wú)需聲明薪捍,可以直接使用甩卓,切記 等號(hào)左右一定不能有空格
引用變量的時(shí)候需要在變量名前面加上$符號(hào)判导,否則bash會(huì)視為字符串執(zhí)行
somevar='test'
echo $somevar
字符串
$(($var*3)) $var是字符串信粮,雙括號(hào)語(yǔ)法支持字符串轉(zhuǎn)數(shù)字坎拐,然后運(yùn)算
sips -Z $((${size_array[i]}*2)) $file_2x
sips -Z $((${size_array[i]}*3)) $file_3x
數(shù)組
當(dāng)有變量為如下格式的時(shí)候箩朴,Bash會(huì)自動(dòng)創(chuàng)建數(shù)組
arrary[index]=value
fruits[0]='apple'
fruits[1]='banana'
fruits[2]='orange'
echo ${fruits[1]}
訪問(wèn)數(shù)組元素使用花括號(hào),${array[index]}
聲明一個(gè)數(shù)組驾孔,并初始化
array=(element1 element2 element3)
輸出整個(gè)數(shù)組
echo ${array[@]}
獲取數(shù)組長(zhǎng)度
${#array[@]}
獲取數(shù)組第n個(gè)元素的長(zhǎng)度
${#array[n]}
#! /bin/bash
Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'
echo ${#Unix[3]} # length of the element located at index 3 i.e Suse
添加數(shù)組元素
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Unix=("${Unix[@]}" "AIX" "HP-UX")
echo ${Unix[7]}
"AIX"和"HP-UX"被添加到數(shù)組的第7位和第8位
刪除數(shù)組元素
使用模式(patterns)刪除數(shù)組元素
按pattern過(guò)濾之后存儲(chǔ)剩余元素到一個(gè)新數(shù)組
#!/bin/bash
declare -a Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora');
declare -a patter=( ${Unix[@]/Red*/} )
echo ${patter[@]}
$ ./arraymanip.sh
Debian Ubuntu Suse Fedora
上面的例子刪除數(shù)組元素形式如Red*
流程控制
條件選擇
-z檢測(cè)字符串長(zhǎng)度為0, -n 檢測(cè)字符串不為0
如果then和if寫(xiě)在同一行的話芍秆,then前面要加;
if [ -z $a ];then
echo '$a is empty'
fi
if - then - else - fi 語(yǔ)法
if [ ${size_array[i]} != "1024" ]
then
file_2x=$out_dir/icon-${size_array[i]}@2x.png
file_3x=$out_dir/icon-${size_array[i]}@3x.png
cp $source_file $file_2x
cp $source_file $file_3x
sips -Z $((${size_array[i]}*2)) $file_2x
sips -Z $((${size_array[i]}*3)) $file_3x
else
file_1024=$out_dir/icon-1024.png
cp $source_file $file_1024
sips -Z 1024 $file_1024
fi
for循環(huán)
打印目錄下所有的文件
#!/bin/bash
for i in $( ls ); do
echo item: $i
done
打印序列
#!/bin/bash
for n in $(seq 1 10);
do
echo $n
done
while循環(huán)
i=2
while [[ $i -le 19 ]]; do
file="demo"$i".js"
echo $file
cp demo1.js $file
let i=i+1
done
until語(yǔ)法
#!/bin/bash
counter=$1
until [ $counter -lt 10 ];
do
echo the counter:$counter
let counter=counter-1
done
函數(shù)
local聲明為局部變量
function hello {
local HELLO=World
echo HELLO
}
比較運(yùn)算
字符串比較運(yùn)算符
比較符 | 說(shuō)明 | 舉例 |
---|---|---|
-z string | 如果長(zhǎng)度為零則為真 | -z $somevar |
-n string | 如果長(zhǎng)度不為零則為真 | -n $somevar |
str1 = str2 | 如果str1與str2相同,則為真 | $str1 = $str2 |
str1 != str2 | 如果長(zhǎng)度為零則為真 | $str1 != $str2 |
算術(shù)比較符
比較符 | 說(shuō)明 | 舉例 |
---|---|---|
-eq | 等于 | $1 -eq 10 |
-ne | 不等于 | $1 -ne 10 |
-lt | 小于 | $1 -lt 10 |
-gt | 大于 | $1 -gt 10 |
-le | 小于或等于 | $1 -le 10 |
-ge | 大于或等于 | $1 -ge 10 |
continue翠勉,break,exit 0
continue妖啥,break和主流語(yǔ)言一致
bash好像不支持return ,可以用exit 0
退出腳本