2015-12-28 46 views
0

您好,这是我早先问题的复现,有什么建议吗?递归函数重复次数,如果语句是“假”

#!/bin/ksh 

test_1() 

{ 
    echo "Trouble" 
} 

invalid_opts() 
{ 
echo $1 
if [ "$1" == "N" ] || [ "$1" == "n" ]; then 
echo "returng $1" 
return 1 
elif [ "$1" == "" ]; then 
echo "returning $1" 
return 1 
else 
echo "returning $1" 
return 0 
fi 
} 

hello() 
{ 
echo "you are in hello, is this ok Y/N" 
read hello_opts 
invalid_opts $hello_opts 
     sleep 2 
    echo $? 
if [ "$?" -eq "1" ]; then 
return 
fi 
echo "choose from the list below" 
cat /home/devteam/dan/sayhello.txt 
read hello_choice 
invalid_opts $hello_choice 
if [ "$?" -eq "1" ]; then 
    echo "Before recursion" 
    hello 
fi 
test_1 
} 

while true 
do 
echo "enter from below 
    1. hello 
    2. hi 
    3. exit " 

read opt 
echo 

case $opt in 
1) hello;; 
2) hi;; 
3) exit ;; 
    esac 
done 

因此,如果你执行上面的脚本,你在递归(回声“递归之前”)之前,如果循环和跳过如果循环之后,你最终会执行善后功能前。 test_1多次递归。我怎样才能修改这个脚本?

样品执行:

./try.sh 
    enter from below 
    1. hello 
    2. hi 
    3. exit 
    1 
    you are in hello, is this ok Y/N 
    y 
    y 
    returning y 
    0 
    choose from the list below 
    hi 
    how 

    returning 

    you are in hello, is this ok Y/N 
    y 
    y 
    returning y 
    0 
    choose from the list below 
    hi 
    how 
    asdasd 
    asdasd 
    returning asdasd 
    Trouble 
    Trouble 
+0

什么是你的代码的问题? – EkcenierK

+0

@KLibby你能执行上面的代码吗?确保你输入了if语句和递归,下次执行时,你最终会执行test_1函数多次你在递归中。 – ady6831983

+0

[递归函数shell]可能的重复(http://stackoverflow.com/questions/34487262/recursive-function-shell) – shellter

回答

2

我认为这是在你的代码结构问题,功能test_1被称为在每种情况下功能hello。因此,当递归调用hello时,它会导致调用函数test_1的次数与函数hello的调用次数相同。如果更改的hello功能的东西的一部分,下面你可以解决这个问题

invalid_opts $hello_choice 
if [[ "$?" != "1" ]]; then 
    test_1 
fi 
echo "Before recursion" 
hello 

我也会推荐使用[[...]]((...))条件语句,而不是使用[..]