function arraydblr { local origarray local newarray local elements local i origarray=($(echo"$@")) newarray=($(echo"$@")) elements=$[ $# - 1 ] for (( i = 0; i <= $elements; i++ )) { newarray[$i]=$[ ${origarray[$i]} * 2 ] } echo${newarray[*]} }
myarray=(1 2 3 4 5) echo"The original array is: ${myarray[*]}" arg1=$(echo${myarray[*]}) result=($(arraydblr $arg1)) echo"The new array is: ${result[*]}"
递归函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#!/bin/bash # using recursion
function factorial { if [ $1 -eq 1 ] then echo 1 else local temp=$[ $1 - 1 ] local result=$(factorial $temp) echo $[ $result * $1 ] fi }
read -p "Enter value: " value result=$(factorial $value) echo"The factorial of $value is: $result"
函数库
创建一个包含脚本中所需函数的公用库文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# filename: myfuncs # my script functions
function addem { echo $[ $1 + $2 ] }
function multem { echo $[ $1 * $2 ] }
function divem { if [ $2 -ne 0 ] then echo $[ $1 / $2 ] else echo -1 fi }
value1=10 value2=5 result1=$(addem $value1$value2) result2=$(multem $value1$value2) result3=$(divem $value1$value2) echo"The result of adding them is: $result1" echo"The result of multiplying them is: $result2" echo"The result of dividing them is: $result3"
.bashrc
可以在用户主目录的 .bashrc 文件中定义函数。
sed 命令 文本替换
1 2 3
# s: 替换命令 # test 替换为 big test echo"This is a test" | sed 's/test/big test/'
对文件中的每一行进行替换:
1 2
# 注意:并不会修改文本文件的数据。它只是将修改后的数据发送到STDOUT。 sed 's/dog/cat/' data1.txt