shell - 将函数名称作为参数传递

时间:2015-02-03 13:50:34

标签: shell

我创建了一个需要一些交互性的shell脚本,所以我做了以下功能:

function check(){
    echo $1
    read ans
    if [ -z $ans ] || [ $ans = "y" ]; then 
        $2 ${*:3}  
    fi 
}

现在我可以使用它:

check "shall I greet?" say_hello oz123 stackoverflow 
check "Do you leave?" say_goodbye

鉴于功能:

function say_hello(){

    echo hello $1
    echo hello $2

}

function say_goodbye(){
    echo "Goodbye..."
}

我通过简单的试验提出了check,证明我是否可以将函数名称作为参数来运行。显然这是有效的,但我不明白为什么。你能解释一下原因吗?

1 个答案:

答案 0 :(得分:1)

为了扩展Etan的评论,这就是man bash所说的:

  

SHELL GRAMMAR

Simple Commands  
A simple command is a sequence of optional  variable  assignments 
followed by  blank-separated  words and redirections, and terminated by a
control operator. The first word specifies the command to be executed,
and  is  passed  as  argument  zero. The remaining words are passed as
arguments to the invoked command.

我希望我之前知道这一点,它可以使bash脚本更加构造,更容易编写和阅读。