A
A
Andrey Chernyshev2014-07-09 22:49:18
bash
Andrey Chernyshev, 2014-07-09 22:49:18

How to organize parsing of arguments and switches in bash?

For example, I call my script like this:
MyPlugin header footer -c
Therefore, the order and number can be anything. Footer and header are arguments, and -c is the execution key.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
KEKSOV, 2014-07-09
@KEKSOV

getopts will help you

V
Vlad Zhivotnev, 2014-07-10
@inkvizitor68sl

Have a look at libshflags
https://debian.pro/files/anlamp/mksite.sh - usage example
https://code.google.com/p/shflags/ the library itself

E
Elena Bolshakova, 2014-07-10
@liruoko

If the script has named parameters (options), it's time to switch from bash to languages ​​richer in structures and libraries like Perl, Python, Ruby. Easier debugging, support, refinement.

A
Andrey Chernyshev, 2014-07-15
@delch

In general, I heaped up such a hell:

for val in [email protected]
do
  loopIndex=$[loopIndex+1]
  if [ ! ${val:0:1} = "-" ]; then
    result=${args[$loopIndex]}
    arguments+=$result
  else
    echo "не соответствие"
  fi
done

This is me trying to get all the arguments of the script, but when I call it like this ./bedi.sh -r header footer
, I echo $arguments displays the headerfooter together, as if it were a string, although at the very beginning I declare the arguments = ()
variable . such an option for parsing arguments and parameters
#!/bin/bash

showopts () {
  while getopts ":pq:" optname
    do
      case "$optname" in
        "p")
          echo "Option $optname is specified"
          ;;
        "q")
          echo "Option $optname has value $OPTARG"
          ;;
        "?")
          echo "Unknown option $OPTARG"
          ;;
        ":")
          echo "No argument value for option $OPTARG"
          ;;
        *)
        # Should not occur
          echo "Unknown error while processing options"
          ;;
      esac
    done
  return $OPTIND
}

showargs () {
  for p in "[email protected]"
    do
      echo "[$p]"
    done
}

optinfo=$(showopts "[email protected]")
argstart=$?
arginfo=$(showargs "${@:$argstart}")
echo "Arguments are:"
echo "$arginfo"
echo "Options are:"
echo "$optinfo"

But he obviously does not make arrays, but I need arrays (

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question