![如何在 Linux shell 脚本中提示输入后调用函数?](https://linux22.com/image/1409280/%E5%A6%82%E4%BD%95%E5%9C%A8%20Linux%20shell%20%E8%84%9A%E6%9C%AC%E4%B8%AD%E6%8F%90%E7%A4%BA%E8%BE%93%E5%85%A5%E5%90%8E%E8%B0%83%E7%94%A8%E5%87%BD%E6%95%B0%EF%BC%9F.png)
标题说明了一切。在我被提示后,我希望 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
这将有助于更好地利用更复杂脚本中的函数。希望这能有所帮助。