如何在shell脚本中调用函数? [英] How to call a function in shell Scripting?

查看:165
本文介绍了如何在shell脚本中调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 shell 脚本,它有条件地调用一个函数.

I have a shell script which conditionally calls a function.

例如:-

if [ "$choice" = "true" ]
then 
  process_install
elif [ "$choice" = "false" ]
then 
  process_exit
fi

process_install()
{
  commands...
  commands...
}

process_exit()
{
  commands...
  commands...
}

请告诉我如何做到这一点.

Please let me know how to accomplish this.

推荐答案

你没有指定哪个 shell(有很多),所以我假设 Bourne Shell,那是我认为你的脚本开始于:

You don't specify which shell (there are many), so I am assuming Bourne Shell, that is I think your script starts with:

#!/bin/sh

请记住用 shell 类型标记以后的问题,因为这将有助于社区回答您的问题.

Please remember to tag future questions with the shell type, as this will help the community answer your question.

您需要在调用函数之前定义.使用 ():

You need to define your functions before you call them. Using ():

process_install()
{
    echo "Performing process_install() commands, using arguments [${*}]..."
}

process_exit()
{
    echo "Performing process_exit() commands, using arguments [${*}]..."
}

然后你可以调用你的函数,就像调用任何命令一样:

Then you can call your functions, just as if you were calling any command:

if [ "$choice" = "true" ]
then
    process_install foo bar
elif [ "$choice" = "false" ]
then
    process_exit baz qux

此时您可能还希望检查无效的选择...

You may also wish to check for invalid choices at this juncture...

else
    echo "Invalid choice [${choice}]..."
fi

查看它以三个不同的 ${choice} 值运行.

祝你好运!

这篇关于如何在shell脚本中调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆