Sponsored Content
Top Forums Shell Programming and Scripting Using getopts for handling multiple options Post 302928143 by drl on Tuesday 9th of December 2014 09:24:56 AM
Old 12-09-2014
Hi.
Quote:
Originally Posted by drl
I seem to recall seeing simple shell code to collect strings until they hit an argument that began with with a [+-] -- so you could roll your own.
Apparently this looked familiar to me because I had written one.

This script, s5, will show 3 methods for accumulating multiple arguments:
Code:
#!/usr/bin/env ksh

# @(#) s5	Demonstrate collecting arguments, splitting arguments.
# -a string can be repeated
# -b delimited string
# -c strings until end or next option
# -d delimiter character

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
# C=$HOME/bin/context && [ -f $C ] && . $C

echo
echo " Args before \"$*\""
aindex=0
cindex=0
# declare -a a	# for bash
# declare -a c	# for bash
err=0
del=","
while getopts a:b:c:d: opt
do
  case $opt in
    a)	a[$aindex]=$OPTARG ; (( aindex++ )) ;;
    b)	b=$OPTARG ;;
    # could use bash/ksh patterns in [[ ]] in place of grep
    
    c)
      db " before c loop, args #, 1, 2 = :$#:, :$1:, :$2:"
      c[$cindex]=$2
      shift
      while [ -n "$1" ] && echo "$2" | grep -v -q '^[-+]'
      do
        c[$cindex]=$1 ; (( cindex++ ))
        shift
        db " at end loop, $# args are [$*]"
      done
	  if [ -n "$1" ]
	  then
        c[$cindex]=$1
	  fi
      KEEPER=$2
      set -- $2 $*
    ;;
    d)	del=$OPTARG ;;
    *)	(( err++ )) ;;
  esac
done
if (( OPTIND-1 <= $# ))
then
shift $(( OPTIND-1 ))
fi
echo " Args after  \"$*\""

[[ $err != 0 ]] && ( echo " Errors: $err, aborting." ; exit 1 )

# Continue processing.
# Display the content of the collected array: a.
if [[ ${#a} > 0 ]]
then
  echo
  echo " Multiply-specified arguments of option a, collected in array:"
  for (( i=0 ; i<${#a[*]} ; i++ ))
  do
    echo " $i ${a[$i]}"
  done
fi

# Continue processing.
# Display the content of the collected array: c.
if [[ ${#c} > 0 ]]
then
  echo
  echo " Collected sequence arguments of option c :"
  for (( i=0 ; i<${#c[*]} ; i++ ))
  do
    echo " $i ${c[$i]}"
  done
fi

# Split the delimiter-separated items.
if [ -n "$b" ]
then
  echo
  echo " Elements that were separated by \"$del\":"
  v=( $( echo "$b" | sed "s/$del/ /g" ) )
  i=0
  for j in ${v[*]}
  do
    echo " $i $j"
    (( i++ ))
  done
fi

exit 0

This is a driver script, run5, that will exercise the methods:
Code:
#!/usr/bin/env ksh

# @(#) run5	Exercise script s5 to demonstrate methods.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { : ; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf
"\n" ) >&2 ; }
C=$HOME/bin/context && [ -f $C ] && . $C

# Test multiply-specified options.
pl " Multiply-specified options:"
./s5 -a alpha -a beta file1 ... filen

# Test comma-separated methods.
pl " Comma-separated methods:"
./s5 -b 3,4,5 file1 ... filen

# Showing unexpected results for -b=..."
pl " Expected anomaly for -b=...:"
./s5 -b=6,7

# Choose a different delimiter:"
pl " Select delimiter \":\" instead of \",\":"
./s5 -d ":" -b 8:9 

# Command not found error when using bare \"|\":"
pl " Expect error for unprotected \"|\":"
./s5 -d | -b 10|11

# Protect \"|\" with quotes:"
pl " Better results for protected pipe symbol:"
./s5 -d "|" -b "10|11"

pl " Collect until new -option letter:"
./s5 -c able baker charlie -a first -a second

pl " Collect again until new -option letter:"
./s5 -c delta echo foxtrot -- file1 file2

pl " Collect once more until new -option letter or end:"
./s5 -c golf hotel india

exit 0

Executing run5 produces:
Code:
$ ./run5

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian 5.0.8 (lenny, workstation) 
ksh 93s+

-----
 Multiply-specified options:

 Args before "-a alpha -a beta file1 ... filen"
 Args after  "file1 ... filen"

 Multiply-specified arguments of option a, collected in array:
 0 alpha
 1 beta

-----
 Comma-separated methods:

 Args before "-b 3,4,5 file1 ... filen"
 Args after  "file1 ... filen"

 Elements that were separated by ",":
 0 3
 1 4
 2 5

-----
 Expected anomaly for -b=...:

 Args before "-b=6,7"
 Args after  ""

 Elements that were separated by ",":
 0 =6
 1 7

-----
 Select delimiter ":" instead of ",":

 Args before "-d : -b 8:9"
 Args after  ""

 Elements that were separated by ":":
 0 8
 1 9

-----
 Expect error for unprotected "|":
./s5: -d: argument expected
./run5: line 33: -b: not found
./run5[33]: 11: not found [No such file or directory]

-----
 Better results for protected pipe symbol:

 Args before "-d | -b 10|11"
 Args after  ""

 Elements that were separated by "|":
 0 10
 1 11

-----
 Collect until new -option letter:

 Args before "-c able baker charlie -a first -a second"
 Args after  ""

 Multiply-specified arguments of option a, collected in array:
 0 first
 1 second

 Collected sequence arguments of option c :
 0 able
 1 baker
 2 charlie

-----
 Collect again until new -option letter:

 Args before "-c delta echo foxtrot -- file1 file2"
 Args after  "file1 file2"

 Collected sequence arguments of option c :
 0 delta
 1 echo
 2 foxtrot

-----
 Collect once more until new -option letter or end:

 Args before "-c golf hotel india"
 Args after  ""

 Collected sequence arguments of option c :
 0 golf
 1 hotel
 2 india

Best wishes ... cheers, drl

( Edit 1: correct minor typo )

Last edited by drl; 12-09-2014 at 05:08 PM..
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

getopts takes options for parameters

Here is my post with a question about getopts. I am running korn shell on Solaris 5.8. I am trying to ensure that certain options require a parameter, which is easy enough. I have found that if multiple options are entered on the command line together, but the parameter for one of the options is... (1 Reply)
Discussion started by: UCD-Randy
1 Replies

2. UNIX for Advanced & Expert Users

Multiple file handling

Dear All, I have two files, which looks like: File 1 124 235 152 178 156 142 178 163 159 File 2 124|5623 452|6698 178|9995 (8 Replies)
Discussion started by: rochitsharma
8 Replies

3. Shell Programming and Scripting

File handling, getopts command in unix

I need to create a shell script having the menu with few options such as 1. Listing 2. Change permissions 3. Modify Contents 4. Delete Files 5. Exit 1. For 1. Listing: Display a special listing of files showing their date of modification and access time (side by side) along with their... (2 Replies)
Discussion started by: bab123
2 Replies

4. UNIX for Advanced & Expert Users

shred multiple options

I've created a wxpython gui for the shred command. I can successfully mix and match all the shred options except two: -size and --random-source. (Man page definitions below). -size and --random-source seem to only work when they are used as the sole option passed. For example, I can zero a... (0 Replies)
Discussion started by: codecellar
0 Replies

5. Programming

Handling Multiple terminals

Hi, Basically I've written a game in ncurses that supports multiple players. Each player has a process associated with him which shares a segment of memory in which the player's structures are stored, and these structured are accessed by the 'server' program and handled there. The scope of the... (13 Replies)
Discussion started by: dgre0018
13 Replies

6. Shell Programming and Scripting

Intersperse arguments and options w/ getopts

Is it possible to get a script that uses getopts to accept options and arguments in any order? eg. -g -h 2 4 works like -g 2 -h 4. (1 Reply)
Discussion started by: lee.n.doan
1 Replies

7. Shell Programming and Scripting

Help with Handling multiple argument in shell script

Hi i have written a shell script that takes only single ip address from the user and calculates its latency and reliability, can you please tell me that what should be done if i want that user should enter 100 or 1000 ip address (5 Replies)
Discussion started by: Preeti_17
5 Replies

8. Shell Programming and Scripting

Multiple variables options

Hi I'm looking to take a user input and use it to effect just two characters in a command rather than having multiple functions for each one. function baseencode() { echo "This function handles the following: $YELLOW base64 base32 base16 $NORMAL" echo "$GREEN Select 64 32 or 16 $NORMAL"... (2 Replies)
Discussion started by: 3therk1ll
2 Replies

9. Shell Programming and Scripting

ISSUE in handling multiple same name files :-(

Dear all, My work is completely stuck cos of the following issue. Please find it here and kindly help me. Task is following: I have set of files with such pattern 1t-rw-rw-r-- 1 emily emily 119 Jun 11 10:45 vgtree_5_1_pfs.root 3t-rw-rw-r-- 1 emily emily 145 Jun 11 10:46 vgtree_5_3_pfs.root... (4 Replies)
Discussion started by: emily
4 Replies

10. Shell Programming and Scripting

SFTP multiple options

Hi, I am trying to SFTP files in a script that i created. But the problem is i have to use -oPort and -b together. how can i get this done. I have tried as below command in my script but with no luck sftp -oPort=102 -b <batchfilename> username@server sftp -oPort=102 -ob... (1 Reply)
Discussion started by: ramkiran77
1 Replies
All times are GMT -4. The time now is 01:13 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy