标题说明了一切。在我被提示后,我希望 yes 和 no 分别调用一个函数。
# Check to see if you ran this script before
echo
echo I need to know if this is your first time...
while true; do
read -p "" yn
case $yn in
[Yy]* ) new;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
# Define function as new
new (){
clear; echo As you are new, I will need a few things.
}
# Define function as root
root(){
echo "$(tput setaf 6)Hello, world$(tput sgr0)"
}
echo
如果用户输入“y”,我希望脚本调用函数“new”。现在,脚本将尝试运行一个名为“new”的不存在的程序。哈哈。谢谢
答案1
您需要在调用函数之前定义它们:
# Define function as new
new (){
clear; echo As you are new, I will need a few things.
}
# Check to see if you ran this script before
echo
echo I need to know if this is your first time...
while true; do
read -p "" yn
case $yn in
[Yy]* ) new;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
答案2
假设这是 bash,脚本中的每一行都将从最小到最大读取。即“第 1 行,然后是第 2 行,然后是第 3 行,依此类推。考虑到这一点,您可以在脚本中创建许多函数,并依次调用它们,如下所示:
#!/bin/bash
func_1() {
echo "Doing something."
}
func_2() {
echo "Doing something again."
}
func_3() {
echo "Doing something for the last time."
}
func_1
func_2
func_3
但是,为了调用每个函数,调用总是必须在定义之后,如下所示:
#!/bin/bash
func_1() {
echo "Doing something."
}
func_2() {
echo "Doing something again."
}
func_3() {
echo "Doing something for the last time."
}
until [ "$SOMETHING" == "SOMETHING_1" ]
do
func_1
done
until [ "$SOMETHING_2" == "SOMETHING_3" ]
do
func_2
done
until [ "$SOMETHING_4" == "SOMETHING_5" ]
do
func_3
done
这将有助于更好地利用更复杂脚本中的函数。希望这能有所帮助。