0
Shell进阶技巧
source link: https://bajie.dev/posts/20220609-shell_tips/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Shell进阶技巧
2022-06-09
2 分钟阅读
Shell脚本的进阶技巧:
一、String 类的技巧
String类当作数组来使用,注意范围的下标,0:4,4最后要被踢掉,实际是0-3,共4个字符:
string="Bash is great!"
echo ${string:8} # great!
echo ${string:0:4} # Bash
echo ${string:8:-1} # great (-1: upto 1st element from right)
fallback
数组的长度:
string="Bash is great!";
len=${#string}
echo "len = $len"
fallback
字符串的替换:
string="Bash is great!!"
echo ${string/Bash/GNU Bash} # GNU Bash is great!!
echo ${string//!/.} # Bash is great..
fallback
大小写替换:
string="Bash"
echo ${string^^} # BASH
echo ${string,,} # bash
fallback
按index存取数组中字符在shell中不可用,但是可以用function变相实现:
function charAt() {
string=$1
i=$2
echo ${string:i:1}
}
echo $(charAt "Hello" 2) # l
echo $(charAt "Hello" 1) # e
fallback
二、数组和字典
定义一个数组并且遍历它:
A=(2 4 5 6 4)
for i in ${A[@]}; do
echo -n "${i} " # 2 4 5 6 4
done
fallback
同样对数组进行切割:
A=(2 4 5 6 4)
echo ${A[@]:2:3} # 5 6 4
echo ${A[@]:0:1} # 2
fallback
Bash 中的数组需要使用 [@]
符号来引用整个数组,可以用简洁的语法对数组增加元素
A=(1 2 3)
A+=(4)
echo ${A[@]} # 1 2 3 4
A+=(5 6)
echo ${A[@]} # 1 2 3 4 5 6
fallback
字典也一样
declare -A D
D=(["one"]=1 ["two"]=2 ["three"]=3)
for i in ${!D[@]}; do
echo "$i -> ${D[$i]}" # one -> 1 ....
done
fallback
三、数学计算
简单的数学计算可以用 $((...))
来完成:
a=10
b=5
echo "$a + $b = $((a + b))" # 10 + 5 = 15
echo "$a - $b = $((a - b))" # 10 - 5 = 5
echo "$a x $b = $((a * b))" # 10 x 5 = 50
echo "$a / $b = $((a / b))" # 10 / 5 = 2
echo "$a % $b = $((a % b))" # 10 % 5 = 0
fallback
或者借助复杂一点的 bc 来完成:
a=10
b=5.7
echo "$a / $b = $(echo "scale = 2; $a / $b" | bc)" # 10 / 5.7 = 1.75
fallback
随机数的产生:
echo $(($RANDOM % 10)) # Random number between 0 and 10
fallback
控制输入变量:
read -p "Enter your name: " name
echo "Hello, $name"
fallback
如果要输入数组:
read -p "Enter numbers: " -a A
echo ${A[@]}
fallback
借助上面的技巧,我们可以写出一些复杂的 shell 脚本了
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK