我有一个Shell脚本,根据条件调用一个函数。
例如:
if [ "$choice" = "true" ]
then
process_install
elif [ "$choice" = "false" ]
then
process_exit
fi
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
请告诉我如何完成这个任务。我有一个Shell脚本,根据条件调用一个函数。
例如:
if [ "$choice" = "true" ]
then
process_install
elif [ "$choice" = "false" ]
then
process_exit
fi
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
请告诉我如何完成这个任务。你没有指定使用哪个shell(有许多种),因此我假设您使用的是Bourne Shell,也就是我认为你的脚本应该以以下方式开始:
#!/bin/sh
()
。process_install()
{
echo "Performing process_install() commands, using arguments [${*}]..."
}
process_exit()
{
echo "Performing process_exit() commands, using arguments [${*}]..."
}
然后你可以调用你的函数,就像调用任何命令一样:
if [ "$choice" = "true" ]
then
process_install foo bar
elif [ "$choice" = "false" ]
then
process_exit baz qux
此时,您可能还希望检查无效的选择...
else
echo "Invalid choice [${choice}]..."
fi
祝你好运!
#!/bin/bash
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
if [ "$choice" = "true" ] then
process_install
else
process_exit
fi
then
之前缺少一个分号。 - camh在bash中使用函数()的示例:
#!/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
return [[ -f "$f" ]]
"会更加简洁,不是吗? - Jonathan Leffler在使用之前需要定义函数。sh中没有预先定义函数的机制,但一种常见的技术是执行以下操作:
main() { case "$choice" in true) process_install;; false) process_exit;; esac } process_install() { 命令... 命令... } process_exit() { 命令... 命令... }
main()
Function Definition : Create a new script file
Function Call : Invoke the script file
概述:
考虑这个名为funcdemo
的脚本:
#!/bin/bash
[ $# = 0 ] && exhort "write nastygram"
exhort(){
echo "Please, please do not forget to $*"
}
[ $# != 0 ] && exhort "write begging letter"
使用中:
$ funcdemo
./funcdemo: line 3: exhort: command not found
$ funcdemo 1
Please, please do not forget to write begging letter
$
#!/bin/bash
# functiontest.sh a sample to call the function in the shell script
choice="true"
function process_install
{
commands...
}
function process_exit
{
commands...
}
function main
{
if [[ "$choice" == "true" ]]; then
process_install
elif [[ "$choice" == "false" ]]; then
process_exit
fi
}
main "$@"