参考: https://seankross.com/the-unix-workbench/bash-programming.html
0x01 数学
expr 5 / 2
# 2
echo "5/2" | bc -l
# 2.50000000000000000000
0x02 变量
a=1
let a=$a+1
# 2
##### $() 命令行计算结果
files=$(ll|wc -l)
echo $files
# 365
##### 入参变量
#!/usr/local/bin/bash
echo "arguments: $@"
echo "arg1 : $1, arg2 : $2"
echo "arg count : $#"
# ./demo.sh aa bb
# arguments: aa bb
# arg1 : aa, arg2 : bb
# arg count : 2
##### 用户输入
read count
echo "Your input : $count"
# hello
# Your input: hello
##### 执行结果
true
echo $?
false
echo $?
# 0
# 1
##### 条件与或 && ||
##### 条件判断
[[ 4 -gt 3 ]]
echo $?
# 0
Logical Flag | Meaning | Usage |
---|---|---|
-gt | 大于 | [[ $planets -gt 8 ]] |
-ge | 大于等于 | [[ $votes -ge 270 ]] |
-eq | 等于 (数字或字符串) | [[ $fingers -eq 10 ]] |
-ne | 不等于 | [[ $pages -ne 0 ]] |
-le | 小于等于 | [[ $candles -le 9 ]] |
-lt | 小于 | [[ $wives -lt 2 ]] |
-e | 文件存在 | [[ -e $taxes_2016 ]] |
-d | 目录存在 | [[ -d $photos ]] |
-z | Length of String is Zero | [[ -z $name ]] |
-n | Length of String is Non-Zero | [[ -n $name ]] |
0x03 正则匹配
bash 不支持 \d \D \s \S \w \W
需要使用下面代替:
[[:digit:]],[^[:digit:]],[[:space:]],[^[:space:]], [_[:alnum:]], [^_[:alnum:]]
-
=~
正则匹配[[ $consonants =~ [aeiou] ]]
-
=
字符串相等[[ $password = "pegasus" ]]
-
!=
字符串不等[[ $fruit != "banana" ]]
-
!
逻辑取反[[ ! "apple" =~ ^b ]]
0x04 IF-ELSE
if [[ $1 -eq 4 ]]
then
echo "$1 is my favorite number"
elif [[ $1 -gt 3 ]]
then
echo "$1 is a great number"
else
echo "You entered: $1, not what I was looking for."
fi
0x05 数组
# 定义数组
fruits=(apple banana orange)
# 使用数组元素
echo ${fruits[0]}
fruits=(blood frogs lice flies sickness boils hail locusts darkness death)
# 打印所有元素
echo ${fruits[*]}
# Slice index:5 length:3
echo ${fruits[*]:5:3}
# 打印数组长度
echo ${#fruits[*]}
# 拼接新数组 +=
fruits+=(apple banana)
echo ${fruits[*]}
fruits+=(pear)
echo ${fruits[*]}
# blood frogs lice flies sickness boils hail locusts darkness death
# boils hail locusts
# 10
# blood frogs lice flies sickness boils hail locusts darkness death apple banana
# blood frogs lice flies sickness boils hail locusts darkness death apple banana pear
0x06 括号
可以生成字符串序列
echo {0..3}
# echo {a..z}{A..Z}
# 0 1 2 3
0x07 循环
for
for i in {0..3}
do
echo "i is equal to $i"
done
# i is equal to 0
# i is equal to 1
# i is equal to 2
# i is equal to 3
words=(sunny wendy randy jobs)
for a in ${words[*]}
do
echo "now word is : $a"
done
# now word is : sunny
# now word is : wendy
# now word is : randy
# now word is : jobs
files=$(ls)
for a in ${files[*]}
do
echo "当前目录文件名 : $a"
done
while
count=3
while [[ $count -gt 0 ]]
do
echo "count now is $count"
let count=$count-1
done
# count now is 3
# count now is 2
# count now is 1
0x08 函数
function hello() {
echo "Hello"
}
# 这里两次调用函数
hello
hello
# Hello
# Hello
# 注意函数名后面的括号可以省掉
function hello2 {
echo "Nice to meet you $1"
}
hello2 小野花
# Nice to meet you 小野花
# 函数返回值
function do_sum {
# 防止污染全局变量 sum
local sum=0
for i in $@
do
let sum=$sum+$i
done
echo $sum
}
# 需要注意: 如何想从函数接收返回值, 需要使用 $()语法
t=$(do_sum {1..5})
echo "result is $t"
# result is 15
接下来看什么?
网友评论