如果语句为" FALSE"则递归函数重复次数。

时间:2015-12-28 21:53:08

标签: shell unix recursion sh ksh

您好,这是我之前提出的问题的重述,有什么建议吗?

#!/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

因此,如果执行上面的脚本,并且在递归之前处于if循环中(echo"在递归之前")并在此之后跳过if循环,则最终将执行aftermath函数ex。 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

1 个答案:

答案 0 :(得分:2)

我认为您的代码结构存在问题,在每种情况下,函数test_1都会调用函数hello。因此,当hello的递归调用解除时,它会导致调用函数test_1和函数hello一样多次。如果您更改hello功能部分如下所示,则可以解决问题

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

我还建议使用[[...]]((...))条件而不是[..]