How-to enforce check on getopts command


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting How-to enforce check on getopts command
# 1  
Old 12-07-2016
How-to enforce check on getopts command

here is my script that expects the user to run it like

Code:
./best.sh -f /tmp/log.txt

more best.sh
#!/bin/bash

while getopts ":f:" opt; do
  case $opt in
    f) file_in="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done

Code:
uname -a
SunOS mymac 5.11 11.2 sun4v sparc sun4v

How can i modify this script to echo an error msg and exit the script incase the user does not specify the -f option in the argument.
# 2  
Old 12-07-2016
Quote:
Originally Posted by mohtashims
How can i modify this script to echo an error msg and exit the script incase the user does not specify the -f option in the argument.
Out of a myriad of other possibilities: introduce a flag, set it to false initially, set it to true in the handling part of the "-f"-option and test for its status afterwards:

Code:
#!/bin/bash

local    opt=""                      # when will you learn to declare what you use?
local    file_in=""                  # input file
local -i lFUsed=0                    # flag f-option was used = false

while getopts ":f:" opt; do
  case $opt in
    f) 
       file_in="$OPTARG"
       # a test for the file being readable/existing would fit nicely here, no?
       lFUsed=1               # change flag when -f was indeed used
       ;;

    \?)
       echo "Invalid option -$OPTARG" >&2
       ;;

  esac
done

if ! (( lFUsed )) ; then
     echo "no f-option was used, Aborting!." >&2
     exit 1
fi

exit 0

I hope this helps.

bakunin

Last edited by bakunin; 12-07-2016 at 08:04 PM..
This User Gave Thanks to bakunin For This Post:
# 3  
Old 12-08-2016
Try also upfront:
Code:
[ "$*" = "${*/-f}" ] && echo NoNoNo - -f missing!

This User Gave Thanks to RudiC For This Post:
# 4  
Old 12-08-2016
Quote:
Originally Posted by RudiC
Try also upfront:
Code:
[ "$*" = "${*/-f}" ] && echo NoNoNo - -f missing!

ahem:

Code:
# cat argtest.sh
#! /bin/bash
[ "$*" = "${*/-f}" ] && echo NoNoNo - -f missing!
exit 0

# ./argtest.sh -ef
NoNoNo - -f missing!

you cannot rely on "-f" being not concatenated with other options although i concede that this works as long as only a single option is concerned.

I hoe this helps.

bakunin
This User Gave Thanks to bakunin For This Post:
# 5  
Old 12-08-2016
Hahaha - you are totally right. Sort of short sighted on my side. I had sth. similar to what you posted in mind but was a bit late, wasn't I?


EDIT:
Something along this line might work (in a recent bash), though:
Code:
[[ "$*" =~ -[^[:space:]]*f ]] && echo OK || echo NOK

(although not THOROUGHLY tested...)

Last edited by RudiC; 12-08-2016 at 08:30 AM..
# 6  
Old 12-08-2016
Bug

Code:
bash-4.1$ more bl.sh
callme()
{
#!/bin/bash

local    opt=""                      # when will you learn to declare what you use?
local    file_in=""                  # input file
local -i lFUsed=0                    # flag f-option was used = false

while getopts ":f:" opt; do
  case $opt in
    f)
       file_in="$OPTARG"
       # a test for the file being readable/existing would fit nicely here, no?
       lFUsed=1               # change flag when -f was indeed used
       ;;
    \?)
       echo "Invalid option -$OPTARG" >&2
       ;;
  esac
done
if ! (( lFUsed )) ; then
     echo "no f-option was used, Aborting!." >&2
     exit 1
fi
exit 0
}
callme

Now executing bl.sh as below.

Code:
./bl.sh -f hello.txt
no f-option was used, Aborting!.

Why is it giving error when it should have worked ?

Can you please tell me whats wrong ??
# 7  
Old 12-08-2016
Quote:
Originally Posted by mohtashims
Why is it giving error when it should have worked ?
Can you please tell me whats wrong ??
Yes: you have put everything - including the shebang line, which makes absoultely no sense - into a function and then called the function with no arguments. What is getopts supposed to work on when there are no options provided, hm?

You could have found that out easily yourself by putting an echo-statement here:

Code:
   f)
       file_in="$OPTARG"
       # a test for the file being readable/existing would fit nicely here, no?
       echo "now in -f option handling"
       lFUsed=1               # change flag when -f was indeed used
       ;;

and you would have immediately noticed that this part was not even executed. You could also have put a testwise echo-statement into the while-loop and show the values of "$opt" and "$OPTARG" during executing which would have yielded the same information. Finally you could have tried the sample script UNMODIFIEDLY first before you tinkered with it.

Don't get me wrong, it is meant to be tinkered with. But trying to understand it first before doing experiments (like putting everything into a function) is usually a good idea.

I hope this helps.

bakunin
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

How to enforce interactive keytool?

i am reading line by line from a file as below while IFS= read -r var do ... ... ... done < "hello.txt" I added the keytool command in the do while loop as below. while IFS= read -r var do ... keytool -genkey -alias $fname -keyalg RSA -keystore $fname.jks -keysize 2048 ... done... (3 Replies)
Discussion started by: mohtashims
3 Replies

2. Shell Programming and Scripting

Getopts how to handle missing '-' in command line args.

I'm using getopts to process command line args in a Bash script. The code looks like this: while getopts ":cfmvhs:t:" option; do case $option in c) operationMode="CHECK" ;; f) operationMode="FAST" ;; m) ... (6 Replies)
Discussion started by: gencon
6 Replies

3. Shell Programming and Scripting

bash:getopts command help

How can I say one of the options is required? can I use an if statement? let say: while getopts ":c:u:fp" opt; do case $opt in c) echo "-c was triggered, Parameter: $OPTARG" >&2;; u) echo "-u was triggered, Parameter: $OPTARG" >&2;; f) echo "-u was triggered,... (2 Replies)
Discussion started by: bashily
2 Replies

4. Shell Programming and Scripting

using getopts to parse a command line

i have the following scenario want to run the following script with manadory and optional argumnets Manadory options are : filename="" port="" optional arguments type -t balances -b bal prices -p ./test filename port -t A -b bal my code i have that won't parse the options is... (1 Reply)
Discussion started by: nano2
1 Replies

5. Shell Programming and Scripting

Help with getopts command

Hello All, I have shell script as below in a.ksh. #! /usr/bin/ksh while getopts a: b: ab:f: VAR do case $VAR in a) A=${OPTARG} echo $A;; b) B=${OPTARG} echo $B;; ab) AB=${OPTARG} echo $AB ;; f) F=${OPTARG} echo $F ;; esac done When I execute sh a.ksh -a 1 -b 2 -ab 3 -f 4 as below... (7 Replies)
Discussion started by: tonsat
7 Replies

6. UNIX for Dummies Questions & Answers

getopts - command line arguments

Hi, I'm having problems with a script where I wanted every single option specified in the command line to have an argument taken with it, but for some reason only d works in the code I will be showing below. For example if I did ./thisfile -a something it would come up with "a chosen with " as... (2 Replies)
Discussion started by: IceX
2 Replies

7. Solaris

How to enforce all users to change their password

Hi All, How to enforce all users to change their password when they try to login. I am having Solaris 9 and 10. Even it would be much better if anyone can say to enforce all users to change their password next morning they login. Thanks in advance, Deepak (3 Replies)
Discussion started by: naw_deepak
3 Replies

8. Solaris

How to enforce login as specific user in Solaris

Hi, I need to implement something that will enforce login to a Solaris server as a particular, specifed user. After this login stage, users will be able to "su -" to whichever user they wish, by which time their activity will be captured by some sort of script (yet to be written). What I need... (7 Replies)
Discussion started by: jamiegeo1
7 Replies

9. 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

10. HP-UX

How to enforce users not to modify their command history.

As a system administrator. sometimes we see the users are trying some commands dangerous for the system health and remove them from their individual coomand history file. How it is possible to enforce that the normal usres will will not be able to modify the history. Thanks in advance. Partha (4 Replies)
Discussion started by: partha_bhunia
4 Replies
Login or Register to Ask a Question