Bash function skill

bash 函数技巧

1. 递归函数

2.导出函数

函数也可以像环境变量一样用 export 导出

1
2
3
4
5
6
7
8
foo() {echo "This is foo function"}
export -f foo
foo () {
echo "This is foo function"
}
➜ foo
This is foo function

3. 读取命令返回值

命令的返回值被保存在变量 $?
返回值被称为 退出状态 。它可用于确定命令执行成功与否。如果命令成功退出,那么退出状态为0,否则为非0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
➜   cat success_test.sh 
#!/bin/bash
#file name: success_test.sh
#对命令行参数求值,比如 success_test.sh `ls | grep txt`
echo "parameter is :"$@

eval $@

if [ $? -eq 0 ];
then
echo "$CMD executed successfully."
else
echo "$CMD terminated unsuccessfully."
fi

执行:

1
2
3
4
5
➜   success_test.sh 'ls'
parameter is :ls
certbot-auto t1 t3 test.sh
success_test.sh t2 test.jsonnet
executed successfully.

4. 向命令传递参数

1
2
3
4
5
6
7
8
➜   cat showArgs.sh
#!/bin/bash

for i in `seq 1 $#`
do
echo $i is $1
shift
done

执行:

1
2
3
4
➜   showArgs.sh a b cc
1 is a
2 is b
3 is cc

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~