Running options in bash script


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Running options in bash script
# 1  
Old 01-11-2018
Running options in bash script

Hello UNIX & Linux Forums community! Long time Linux daily user hobbyist, new to shell scripting....

I'm working on a script that does all the "work" in one script, and makes calls to a second script to display info to the user via mostly expanding variables in heredocs.

I'm contemplating a -q --quiet option to stop the info displaying. Being new to this, I've thought through and tested the following.

However, I'm at a loss as to the terminology used for what I'm trying to do. That leaves me at a loss to find out if my method would be considered bad scripting, and if so, what would be a more appropriate method to easily implement a --quiet option.

The scripts are quite tested and working well at this point. This is more of an afterthought and mental exercise than something really needed.

BTW, I'm manually parsing options without using getopts. I could post the scripts, around 300 lines total, if needed. It's a (current version) bash script, running Arch Linux if it matters. (mostly current version prog's)

Code:
#!/bin/bash


mainfunc () {
    echo "run mainfunc commands"
    $switch    
}

optfunc () {
    echo "run user info extras"
}



normal () { switch=optfunc
}
quiet () { switch=  
}


while    :; do
    case "${1}" in
        -R)     normal ; mainfunc     ;;
       -Rq)     quiet  ; mainfunc    ;;
         *)    break
    esac
    shift
done

# 2  
Old 01-12-2018
Why aren't you using getopts? Having consistent methods of parsing options greatly contributes to the ability of users unfamiliar with your code automatically know how to get a quick view of the syntax of your utility (with something like: utility -?), the ability to specify options separately or combined and in any order:
Code:
utility -Rq
utility -qR
utility -R -q
utility -q -R

should all produce the same results. And, you should have a built-in help/usage message if an unknown option is found. Instead, your code silently ignores unknown options (leading users to believe that the options they provided were correct when, instead, nothing will be done by your code).

You generally want to set flags while processing options, not run the functions that the options indicate should be run (after you have determined all of hte options that are present).

Your code seems to indicate that the -R option in your utility must always be present. Why have an option if it is always required to be set?
This User Gave Thanks to Don Cragun For This Post:
# 3  
Old 01-12-2018
I can think of two methods of implementing a quiet mode. First, use redirections.

Code:
if [ "${quietmode}" = "yes" ]
then 
   exec >/dev/null
fi
printf "this will not be printed in quiet mode\n"
printf "this is a required message and will be printed\n" > /dev/tty

Alternatively:
Code:
if [ "${quietmode}" = "yes" ]
then
   exec 3>/dev/null
else
   exec 3>&1
fi
printf "This won't be printed in quiet mode\n" >&3
printf "This will always be printed\n"

The other way is to use a function:
Code:
function myprint() {
   local mode=$1
   shift
   if [ "${mode}" = normal ] && [ "${quietmode}" = "yes" ]
   then
      return
   fi
   printf "$@"
}

myprint normal "this will not be printed in quiet mode\n"
myprint quiet "this will be printed always\n"

Untested.

Andrew
This User Gave Thanks to apmcd47 For This Post:
# 4  
Old 01-12-2018
Thanks for replies.

Second time someone asked why not using getopts. I have not looked into it so far, although I probably should.

With manually parsing options, I consider each argument as an operation rather than an option. No real option ability...

When the program is called with no operations, or a non existent op, they get this or in the former, without the error message.:

Code:
$ aurt -qR

  Input Error: Please try again or see    aurt --help

 |=====================================================================================|
 |    Aurt, a tiny AUR helper script.         USAGE:  $ aurt [operation] [package]     |
 |-------------------------------------------------------------------------------------|
 | -S  Install Update                -F  Files Provided By Pkg          NOTES:         |
 | -Sv Update By Version             -s  Search For Pkg                                |
 | -Sf Force Install Update          -p  Pacman Log                                    |
 | -R  Remove Pkg And Bld Dir        -h  Help                      leafpad-aurt: lat   |
 | -C  Ck All Pkgs For Updates                                  thunar-base dir: tbd   |
 | -D  Package Dependency Details                              Orphans:  R $(p -Qtdq)  |
 |=====================================================================================|

The scripts:
Code:
https:bbs.archlinux.org/viewtopic.php?id=232437

I was contemplating using the --quiet "option" with the -S and -Sv operations only, as the rest couldn't use --quiet.

I read getopts will not take long options? My script needs the ability to process package names, ie: aurt -S <package name> That and manually parsing them seemed more straight forward to me when I started, likely because of my inexperience.

At this point, it sounds like I need to get my head around understanding getopts and figure out how to deal with the program names separately?

Just reading the replies from you guys gives my more things to research, test, and think about.
# 5  
Old 01-12-2018
getopt does not prevent you from getting package names. That's not what "long options" means also, long options means double-dash-word options like --quiet.
# 6  
Old 01-12-2018
In addition to what Corona688 already said (although I think he meant getopts instead of getopt), in your example:
Code:
aurt -S <package name>

<package name> is either a -S option option-argument or an aurt operand; not an option. You haven't given us enough information to know which you intended in your example. The getopts utility does not place any length limit on option-argument nor operand strings.

Furthermore with many versions of the Korn shell, the built-in getopts utility can handle long and short options (although some ksh man pages fail to document this feature). The method ksh uses doesn't work on bash version 3.2.57. I don't know if it works on bash 4.x version and, you haven't said what version of bash you're using.

To investigate this further, check the thread ksh parsing arguments in a string rather than from the cmdln.
# 7  
Old 01-15-2018
Hi.

There are many schemes / methods / alternatives to help process command line -- CLI -- options. Here are a few. Some take a bit of effort to learn, but they will be time-savers in future work.

I especially like the ones that create man-like pages, and help displays automatically ... cheers, drl
Code:
Process command-line (CLI) options, arguments

        1) getopts, builtin, bash, ksh, zsh
           http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options
           Also, search for option processing, including:
           http://mywiki.wooledge.org/ComplexOptionParsing

        2) perl: many, including libgetopt-euclid-perl, which
           creates man page, help automatically

        3) getopt, enhanced getopts, part of the util-linux, allows GNU "--"
           Examples: /usr/share/doc/util-linux/examples, 2016.03.27

        4) argp.sh, wrapper for getopt, creates man and help (text, XML), etc.
           Allows mixed options and arguments.
           Compiled argp.c -> argp for faster execution.
           https://sourceforge.net/projects/argpsh/, 2016.03.27

        5) shflags, wrapper for getopt, creates help, allow mixed options
           and arguments
           https://github.com/kward/shflags, 2016.08.01

        6) ksh getopts, enhanced, process GNU "--", creates man, help, etc.
           Examples: Learning the Korn Shell, O'Reilly, 2nd, p 380ff

        7) zsh zparseopts
           man zshmodules, part of zshutil

        8) Suggested option names:
           http://www.shelldorado.com/goodcoding/cmdargs.html#flagnames

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Running a remote script with automatic options

I'm trying to run a script that will remotely copy another script to remote host and run copied script to remote server with automatic options- #! /bin/bash HOSTNAME="1 2" for HOST in $HOSTNAME; do scp diskFrag.sh login@$HOST:/home/login sleep 30 ssh login@$HOST... (2 Replies)
Discussion started by: Mannu2525
2 Replies

2. Shell Programming and Scripting

Bash shell script to check if script itself is running

hi guys we've had nagios spewing false alarm (for the umpteenth time) and finally the customer had enough so they're starting to question nagios. we had the check interval increased from 5 minutes to 2 minutes, but that's just temporary solution. I'm thinking of implementing a script on the... (8 Replies)
Discussion started by: hedkandi
8 Replies

3. Shell Programming and Scripting

script running by sh but not by bash

execute the attached script as, bash -x INFA_MAP_GEN_XML.sh "/export/home/e120945/INFORMATICA_MAPPING_GENERATOR/SOURCE" "INFA_TEMPLATE.csv" "/export/home/e120945/INFORMATICA_MAPPING_GENERATOR/TARGET" "UNIX" "/export/home/e120945/INFORMATICA_MAPPING_GENERATOR/SETUP"... (5 Replies)
Discussion started by: 120945
5 Replies

4. Shell Programming and Scripting

Reading command line options from bash script

I have the following code and I am calling it using ./raytrac.bash -u and getting problems. For some reason opt_usage is still 0. opt_usage=0 iarg=0 narg=$# while (($iarg < $narg)) do (( iarg = $iarg + 1 )) arg=$argv usrInputFlag=`echo $arg | awk '/=/ {print 1}; ! /=/... (22 Replies)
Discussion started by: kristinu
22 Replies

5. UNIX for Advanced & Expert Users

how to add new options in bash script

what i want to be is that i would like to reinvent new options that have the same functionality as ... -u is the same functionality of conv=ucase and -l have the same functionality as conv=lcase... is there a way that i can put these in my script so that whenever i will typed in command... (12 Replies)
Discussion started by: aphryllyn1
12 Replies

6. Homework & Coursework Questions

how to create new options of "dd command" using bash script?

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: Creating bash script the dd command and its new options (-l -U) -l options to lowercase contents of file -U... (2 Replies)
Discussion started by: katherineskye1
2 Replies

7. UNIX for Dummies Questions & Answers

Running set options from the command line and bash command

I'm reading about debugging aids in bash and have come across the set command. It says in my little book that an addition to typing set you can also use them "on the command line when running a script..." and it lists this in a small table: set -o option Command Line... (5 Replies)
Discussion started by: Straitsfan
5 Replies

8. Shell Programming and Scripting

bash script to compile multiple .c files with some options

I'm trying to write a bash script and call it "compile" such that running it allows me to compile multiple files with the options "-help," "-backup," and "-clean". I've got the code for the options written, i just can't figure out how to read the input string and then translate that into option... (5 Replies)
Discussion started by: travis.batzer
5 Replies

9. Shell Programming and Scripting

Script running in bash 3.0 not in 3.2

I have wasted one working day writing this scripts. It compares two folders and make a good tabbed report about their differences. #!/bin/bash function DRAW_DEPTH () { ROUND=$1 while do printf %s " " ROUND=`expr $ROUND - 1` done printf %s "|- " } function MAIN () {... (9 Replies)
Discussion started by: trutoman
9 Replies

10. Shell Programming and Scripting

Passing options to a bash script

I'm just not sure where to start looking into this. I want to be able to create switches for my script. Back in the day I'd make my scripts interactive...you know: echo "what report do you want" echo "A)boxes with errors" echo "B)boxes with more than 5 errors" echo "C)Service groups that have... (3 Replies)
Discussion started by: DeCoTwc
3 Replies
Login or Register to Ask a Question