实战演练

  • 定义函数
function fname() {
    statements;
}
或
fname() {
    statements;
}
  • 使用函数名调用函数
fname
  • 参数可以传递给函数,并由脚本进行访问:
[root@shaofeng ~]# fname 1 2;
1, 2
1 2
1 2
[root@shaofeng ~]# cat .bashrc
PS1="[\u@\h \W]\\$ "

isExisted() {
[ -d "$1" ];
}

prepend() {
[ -d "$2" ] && eval $1=\"$2\$\{$1:+':'\$$1\}\" && export $1;
}
alias rm='cp $1 ~/backup && rm $1'

function fname() {
        echo $1, $2;
        echo "$@";
        echo "$*"
        return 0
}

补充内容

  • 递归函数
F() {
        echo $1;
        F hello;
        sleep 1;
}
  • 导出函数,函数的作用可以扩展到子进程中
[root@shaofeng ~]# cat .bashrc

function fname() {
        echo $1 $2;
        echo "$@";
        echo "$*"
        return 0
}

export -f fname
  • 读取命令返回值:./fname_test.sh下面的三行空格,是因为export了,所有执行了fname($CMD)
[root@shaofeng ~]# ./fname_test.sh



fname executed successfully
[root@shaofeng ~]# cat ./fname_test.sh
#!/bin/bash

CMD="fname"
$CMD
if [ $? -eq 0 ];
then
        echo "$CMD executed successfully"
else
        echo "$CMD excuted unsuccessfully"
fi
  • 向命令传递参数
command -p -v -k 1 file
command -pv -k 1 file
command -vpk 1 file
command file -pvk 1

results matching ""

    No results matching ""