我有一个有条件地调用函数的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)
祝好运!
#!/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)
在 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)