shell函数
定义与调用函数:
[student@myhost ~]$ function a(){ echo a function; }
[student@myhost ~]$ a
a function
[student@myhost ~]$ b(){ echo a function; }
[student@myhost ~]$ b
a function
参数传递:
[student@myhost ~]$ c(){ echo $0;echo $1;echo $2;echo $@;echo $*; } #$*扩展为“$1c$2”,c为IFS的第一个字符。$@被扩展为“$1” “$2”
[student@myhost ~]$ c 1 2
bash
1
2
1 2
1 2
递归函数,Fork炸弹:
[student@myhost ~]$ :(){ :|:; };:
以上函数通过创建以2的指数递增创建子进程,最终耗尽服务器资源。可在/etc/security/limits.conf中添加以下内容避免fork炸弹:
用户名 - nproc 20 #含义为指定用户最多创建20个子进程
可用export导出函数,使其在子进程中也可使用:
export -f 函数名
获取命令的执行返回状态:
命令;echo $?
以上若返回0则执行成功,非0则失败。
浙公网安备 33010602011771号