函数
定义函数
function_name(){
# 函数体 在函数中执行的命令行
commands...
# 参数返回 return语句可选,如果没有return语句,则以函数最后一条命令的运行结果作为返回值
如果使用return 则return后跟数值n(数值范围0~255)
[ return int; ]
}
保留字function 和函数名后面的()二者 可以省略其一
省略了()函数定义
function 函数名{
函数体
}
省略了function函数定义
函数名(){
函数体
}
lsal.sh 脚本内容如下
定义函数
#!/bin/bash lsal(){ pwd ls -al } lsal # 函数必须在被调用之前定义
[root@VM-4-2-centos myscript]# vim lsal.sh [root@VM-4-2-centos myscript]# chmod +x lsal.sh [root@VM-4-2-centos myscript]# ./lsal.sh /root/myscript total 68 drwxr-xr-x 2 root root 4096 Aug 27 17:07 . dr-xr-x---. 22 root root 4096 Aug 27 17:07 .. -rwxr-xr-x 1 root root 20 Aug 27 09:36 arg-count.sh -rwxr-xr-x 1 root root 53 Aug 26 17:58 arg.sh -rwxr-xr-x 1 root root 51 Aug 6 15:10 args.sh -rwxr-xr-x 1 root root 158 Aug 27 11:38 arr-del.sh -rwxr-xr-x 1 root root 112 Aug 25 11:19 case_test.sh -rw-r--r-- 1 root root 0 Aug 6 14:55 conf.txt -rw-r--r-- 1 root root 451 Jul 28 17:52 cut_nginx_log.sh -rw-r--r-- 1 root root 240 Jul 30 17:16 first.sh -rwxr-xr-x 1 root root 52 Aug 27 16:36 for.sh
变量的作用域