You are not logged in.

#1 2014-05-09 20:35:01

publicus
Member
Registered: 2014-01-01
Posts: 129

[RESOLVED] How I pass in my command-line variables disgusts me

Hello,

What I'm trying to do is to make an easily configurable script that the user can run with just a few basic command line variables (some of our users are not programmers.)  Now, here's my problem, when it comes to extracting the variables from the command line, it's kind of messy.  Lets say I have the following command:

$ ./hl_script.sh --config-file=config_abc.txt --rate=5000 --data-dump=/opt/dump_area -v

"-v" means verbose

Now, given the weird arrangement of the different types of command line arguments, I'd like to extract the salient parts of the information that I care about.  However, at this moment, all I have is the "cut" command which can easily get into undefined behavior territory should the user misstype an input.  I would love to know how you have done this and what your approach to this problem is.

This is the code that I have so far:

  # this is where we run the initial test and check if the user entered the
  #   help flag in order to see how to properly use this application.
  if [ $# -gt 1 ]; then
    for argument in $@
    do  
      if [ $argument = "--help" ]; then
        echo "Here is how you would use this software and the flags that would"
        echo " be useful."
        echo "  --help"
        echo "    Brings up this display and shows a listing of the options"
        echo "    that can be used to better utilize this app."
        echo ""
        echo "  --config-file=N"
        echo "    Specify the config file that we'd like to use."
        echo ""

        exit 0

      elif [ `cut $argument | cut -d'=' -f 1` = "--config-file" ]; then
        # read-in the config file that we specified and then proceed to set a
        #   bunch of environment variables that we need.
        echo "stuff..."
      fi  
    done
  fi  

Last edited by publicus (2014-05-13 13:13:43)

Offline

#2 2014-05-09 20:50:38

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 20,346

Re: [RESOLVED] How I pass in my command-line variables disgusts me

I know your sample code is Bash, but you may want to consider doing it in Python and using this library
Here is a simple Python program I wrote that uses the library:

ewaller$@$odin ~/devel/python 1004 %./sieve.py
Usage: sieve.py [options] arg

sieve.py: error: incorrect number of arguments
ewaller$@$odin ~/devel/python [2]1005 %./sieve.py 10
2 3 5 7 
ewaller$@$odin ~/devel/python 1006 %./sieve.py --help
Usage: sieve.py [options] arg

Find prime numbers using a sieve of Eratosthenes

Options:
  -h, --help     show this help message and exit
  -v, --verbose  
ewaller$@$odin ~/devel/python 1007 %./sieve.py 10 -v  
removing 4
removing 6
removing 8
removing 10
removing 6
removing 9
removing 10
2 3 5 7 
ewaller$@$odin ~/devel/python 1008 %cat sieve.py 
#! /usr/bin/python
"""
Implement a sieve of Eratosthenes 
"""

from optparse import OptionParser


def main():
    #Handle all the command line nonsense.  We need a number as an argument

    usage = "%prog [options] arg"
    description = "Find prime numbers using a sieve of Eratosthenes"
    parser = OptionParser(usage=usage,description=description)
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    try:
        maxval=eval(args[0])
    except:
        parser.error ("Argument is not a number")
    # Here is the sieve
    a=[x for x in range(0,maxval+1)]
    for count in range(2,int(maxval/2)+1):
        if a[count]:
            for i in range(count*2,maxval+1,count):
                a[i]=0
                if options.verbose:
                    print ("removing %i"%i)
    # and report the results
    
    wrap=0
    for count in range(2,len(a)):
        if a[count]:
            print (count,end=" ")
            wrap += 1
            if (wrap == 5):
                print()
                wrap = 0
    print ()
if __name__ == "__main__":
    main()
ewaller$@$odin ~/devel/python 1009 %

Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#3 2014-05-09 20:57:17

ukhippo
Member
From: Non-paged pool
Registered: 2014-02-21
Posts: 366

Re: [RESOLVED] How I pass in my command-line variables disgusts me

Use getopt.

See /usr/share/doc/until-linux/getopt/getopt-parse.bash for an example

Offline

#4 2014-05-12 14:38:58

publicus
Member
Registered: 2014-01-01
Posts: 129

Re: [RESOLVED] How I pass in my command-line variables disgusts me

ewaller wrote:

I know your sample code is Bash, but you may want to consider doing it in Python and using this library
Here is a simple Python program I wrote that uses the library:

ewaller$@$odin ~/devel/python 1004 %./sieve.py
Usage: sieve.py [options] arg

sieve.py: error: incorrect number of arguments
ewaller$@$odin ~/devel/python [2]1005 %./sieve.py 10
2 3 5 7 
ewaller$@$odin ~/devel/python 1006 %./sieve.py --help
Usage: sieve.py [options] arg

Find prime numbers using a sieve of Eratosthenes

Options:
  -h, --help     show this help message and exit
  -v, --verbose  
ewaller$@$odin ~/devel/python 1007 %./sieve.py 10 -v  
removing 4
removing 6
removing 8
removing 10
removing 6
removing 9
removing 10
2 3 5 7 
ewaller$@$odin ~/devel/python 1008 %cat sieve.py 
#! /usr/bin/python
"""
Implement a sieve of Eratosthenes 
"""

from optparse import OptionParser


def main():
    #Handle all the command line nonsense.  We need a number as an argument

    usage = "%prog [options] arg"
    description = "Find prime numbers using a sieve of Eratosthenes"
    parser = OptionParser(usage=usage,description=description)
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    try:
        maxval=eval(args[0])
    except:
        parser.error ("Argument is not a number")
    # Here is the sieve
    a=[x for x in range(0,maxval+1)]
    for count in range(2,int(maxval/2)+1):
        if a[count]:
            for i in range(count*2,maxval+1,count):
                a[i]=0
                if options.verbose:
                    print ("removing %i"%i)
    # and report the results
    
    wrap=0
    for count in range(2,len(a)):
        if a[count]:
            print (count,end=" ")
            wrap += 1
            if (wrap == 5):
                print()
                wrap = 0
    print ()
if __name__ == "__main__":
    main()
ewaller$@$odin ~/devel/python 1009 %

The thing is, I already have some shell code written that works, so I don't want to re-write (and re-test) that.

Offline

#5 2014-05-12 14:40:17

publicus
Member
Registered: 2014-01-01
Posts: 129

Re: [RESOLVED] How I pass in my command-line variables disgusts me

ukhippo wrote:

Use getopt.

See /usr/share/doc/until-linux/getopt/getopt-parse.bash for an example

My primary issue is this.  How would I handle something if I wanted to pass in a parameter looking like so:

./scripty --version --config-file=config.txt --verbose

It's the --config-file=config.txt that's making me scratch my head.

Offline

#6 2014-05-12 15:38:25

oliver
Member
Registered: 2007-12-12
Posts: 448

Re: [RESOLVED] How I pass in my command-line variables disgusts me

as mentioned, getopt supports having a flag require an argument.

What I can never remember is whether getopt or getopts is the best way to go (they do differ)

Offline

#7 2014-05-12 15:43:22

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: [RESOLVED] How I pass in my command-line variables disgusts me


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#8 2014-05-13 13:13:27

publicus
Member
Registered: 2014-01-01
Posts: 129

Re: [RESOLVED] How I pass in my command-line variables disgusts me

skanky wrote:

See these two links for a useful discussion:

http://mywiki.wooledge.org/BashFAQ/035

Thanks.  That first link did the trick.

Offline

Board footer

Powered by FluxBB