Home > OS >  If ... Else ... If.... Bash
If ... Else ... If.... Bash

Time:09-25

Good Morning!

I have (3) scenarios going with inputs and I cant wrap my head around on how to solve this.

  • host=$1 (name)
  • info=$2 (info)
  • type=$3 (a, b)

name >> info > code will update with new supplied info

name >> info >> type > code will update with new supplied info by type

name >> type > the prompt type will update the info

Im trying to figure out how I can skip over the 2nd input in one of the scenarios above.

Any help is appreciated. Thanks!

if [ "$type" == "a" ]; then
  if [ $# -ne 2 ]; then
      usage1
  fi

elif [ "$type" == "b" ]; then
  if [ $# -ne 3 ]; then
      usage2
  fi

else
    if [ $# -ne 2 ]; then
       usage
    fi
fi


if [ "$type" == "a" ]; then
  ...command
  ...command

elif [ "$type" == "b" ]; then
  ...command
  ...command

else
  ...command
  ...command
fi

CodePudding user response:

The question is incomplete. If the script receives only two parameters, then you have to decide whether you want to treat them as "name and info" or "name and type". If there is some way of distinguishing between "info" and "type" based on the input, you could parse them and make a decision. But you need to provide the criteria for that decision in the question. On reasonable method (that fails with the csh family) is to use the environment rather than parameters and call the script as:

$ name=foo type=bar ./myscript

For the csh family, you can do the same thing using env.

CodePudding user response:

I think you need to read help for getopt and getopts commands and create more user-friendly argument parsing, like

script --host=blabla --info=blabla --type-blabla

look through arguments with getopts or getopts alows you to provide arguments in any order or even skip them. You can also write your own bicycle to parse arguments.

  • Related