如何在shell Scripting中调用函数?

use*_*206 21 shell

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

例如:-

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

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

process_exit()
{
  commands...
  commands...
}
Run Code Online (Sandbox Code Playgroud)

请让我知道如何做到这一点.

Joh*_*web 22

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

#!/bin/sh
Run Code Online (Sandbox Code Playgroud)

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

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

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

process_exit()
{
    echo "Performing process_exit() commands, using arguments [${*}]..."
}
Run Code Online (Sandbox Code Playgroud)

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

if [ "$choice" = "true" ]
then
    process_install foo bar
elif [ "$choice" = "false" ]
then
    process_exit baz qux
Run Code Online (Sandbox Code Playgroud)

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

else
    echo "Invalid choice [${choice}]..."
fi
Run Code Online (Sandbox Code Playgroud)

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

祝好运!

  • 我的示例定义了调用它们之前(即脚本中较早的部分)的函数。 (3认同)

use*_*057 9

#!/bin/bash

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

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


if [ "$choice" = "true" ] then
    process_install
else
    process_exit
fi
Run Code Online (Sandbox Code Playgroud)

  • 你在'then`之前错过了一个分号. (4认同)
  • +1并欢迎使用Stack Overflow.你的答案说明了该做什么 - 但也会从一点点解释中受益.提问者可能没有发现你所写的内容和他们所得到的内容之间的显着差异. (3认同)

Aut*_*ira 5

在 bash 中使用 function() 的示例:

#!/bin/bash
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
usage(){
    echo "Usage: $0 filename"
    exit 1
}

# define is_file_exists function
# $f -> store argument passed to the script
is_file_exists(){
    local f="$1"
    [[ -f "$f" ]] && return 0 || return 1
}
# invoke  usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage

# Invoke is_file_exits
if ( is_file_exists "$1" )
then
 echo "File found: $1"
else
 echo "File not found: $1"
fi
Run Code Online (Sandbox Code Playgroud)