Shell进阶技巧

目录

Shell脚本的进阶技巧:

一、String 类的技巧

String类当作数组来使用,注意范围的下标,0:4,4最后要被踢掉,实际是0-3,共4个字符:

1string="Bash is great!"
2
3echo ${string:8} # great!
4echo ${string:0:4} # Bash
5echo ${string:8:-1} # great (-1: upto 1st element from right)

数组的长度:

1string="Bash is great!";
2len=${#string}
3echo "len = $len"

字符串的替换:

1string="Bash is great!!"
2echo ${string/Bash/GNU Bash} # GNU Bash is great!!
3echo ${string//!/.} # Bash is great..

大小写替换:

1string="Bash"
2echo ${string^^} # BASH
3echo ${string,,} # bash

按index存取数组中字符在shell中不可用,但是可以用function变相实现:

1function charAt() {
2    string=$1
3    i=$2
4    echo ${string:i:1}
5}
6echo $(charAt "Hello" 2) # l
7echo $(charAt "Hello" 1) # e

二、数组和字典

定义一个数组并且遍历它:

1A=(2 4 5 6 4)
2for i in ${A[@]}; do
3    echo -n "${i} " # 2 4 5 6 4
4done

同样对数组进行切割:

1A=(2 4 5 6 4)
2echo ${A[@]:2:3} # 5 6 4
3echo ${A[@]:0:1} # 2

Bash 中的数组需要使用 [@] 符号来引用整个数组,可以用简洁的语法对数组增加元素

1A=(1 2 3)
2A+=(4)
3echo ${A[@]} # 1 2 3 4
4A+=(5 6)
5echo ${A[@]} # 1 2 3 4 5 6

字典也一样

1declare -A D
2D=(["one"]=1 ["two"]=2 ["three"]=3)
3for i in ${!D[@]}; do
4    echo "$i -> ${D[$i]}" # one -> 1 ....
5done

三、数学计算

简单的数学计算可以用 $((...)) 来完成:

1a=10
2b=5
3
4echo "$a + $b = $((a + b))" # 10 + 5 = 15
5echo "$a - $b = $((a - b))" # 10 - 5 = 5
6echo "$a x $b = $((a * b))" # 10 x 5 = 50
7echo "$a / $b = $((a / b))" # 10 / 5 = 2
8echo "$a % $b = $((a % b))" # 10 % 5 = 0

或者借助复杂一点的 bc 来完成:

1a=10
2b=5.7
3
4echo "$a / $b = $(echo "scale = 2; $a / $b" | bc)" # 10 / 5.7 = 1.75

随机数的产生:

1echo $(($RANDOM % 10)) # Random number between 0 and 10

四、输入

控制输入变量:

1read -p "Enter your name: " name
2echo "Hello, $name"

如果要输入数组:

1read -p "Enter numbers: " -a A
2echo ${A[@]}

借助上面的技巧,我们可以写出一些复杂的 shell 脚本了


Javascripts中的promise
Javascripts中if的优化
comments powered by Disqus