문제

I want to push my input parameters through two sets of checks. Each of these checks is a function. So case would not work because in KSH.Case will "esac" after satisfying the 1st condition.

    die () {
        echo "ERROR: $*. Aborting." >&2
        exit 1
    }

    var=$1
    var1=$2
    [  -z "$var1" ] && var1=$var
    echo "var is $var . Var1 is $var1 "


    # test $var1 != $var2 ||
    dtc() {
  # small function where I am checking if the input parameter is a valid date
    }

    vlc(){
# function where I am checking if the input parameters year is after 2012, because earlier years cannot exist 
}

if dtc  $var && dtc  $var1
then
  if vlc $var && vlc $var1
  then
  stuff
  else
  die "message"
  fi
else
  die "message"
fi

The nested if looks a bit clumsy. If there is a more elegant way convey this to shell.

도움이 되었습니까?

해결책

Improving your indentation will go a long way toward readable code.

If your die message are different, then you have no choice. If they are the same, then you can combine the conditions:

If you just want to die if not all the commands are successful, you can write

dtc "$var" && dtc "$var1" &&
vlc "$var" && vlc "$var1" || die "message"
# OK, all passed
stuff

One style tip for if-else is to put the shorter block first

if ! { dtc "$var" && dtc "$var1"; }
then
    die "message 1"
else
    if ! { vlc "$var" && vlc "$var1"; }
    then
        die "message 2"
    else
        we will do 
        lots of stuff 
        here
    fi
fi

and of course, functions to encapsulate code

stuff() {
    we will do 
    lots of stuff
    here
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top