Sample Header Ad - 728x90

Unix & Linux Stack Exchange

Q&A for users of Linux, FreeBSD and other Unix-like operating systems

Latest Questions

0 votes
2 answers
86 views
More than 1 option when launch script
Is there a way to pass more than one option when running a script? My script has this case: case "$1" in b) backup_start $1 ;; h) _usage ;; *) echo 'Invalid option, -h for help' ;; esac I run my script with: myscript -b backupname But sometimes I would like to run the script with an option with anot...
Is there a way to pass more than one option when running a script? My script has this case: case "$1" in b) backup_start $1 ;; h) _usage ;; *) echo 'Invalid option, -h for help' ;; esac I run my script with: myscript -b backupname But sometimes I would like to run the script with an option with another argument...that I will then use in case inside the script: myscript -b backupname -t mynewarg
ancoling67 (109 rep)
Mar 9, 2025, 07:56 PM • Last activity: Mar 14, 2025, 07:11 PM
0 votes
1 answers
29 views
Trying to sort with getopts with different commands and cannot sort by price
I am trying to sort an inventory list in unix/linux below. I am successful in sorting by name and ID and able to pull up the usage menu but cannot sort by price, even with an "awk" function. I call the code with `./invOpt -p` and the output continues to tell me it's an `invalid option: -p` then pull...
I am trying to sort an inventory list in unix/linux below. I am successful in sorting by name and ID and able to pull up the usage menu but cannot sort by price, even with an "awk" function. I call the code with ./invOpt -p and the output continues to tell me it's an invalid option: -p then pulls up the usage menu below. I'm confused because it refuses to sort the 4th field where the price is. I don't know if the $ and/or the comma sign is messing up the sorting
"Usage: invOpts -i | -n | -p | -h
"  -i  sort by product ID"
"  -n  sort by product name"
"  -p  sort by price"
"  -h  display usage"
INVENTORY MENU:
Product ID   Product Name               	Quantity   Price       	Total Value
-----------  ------------------------------ --------   -----       	-----------
P101     	Apple MacBook Pro          	25     	$2,399.99   	$59,999.75
P102     	Samsung Galaxy S23         	40     	$799.99     	$31,999.60
P103     	Apple iPhone 15            	60     	$999.99     	$59,999.40
P104     	Google Pixel 8             	35     	$899.99     	$31,499.65
P105     	Microsoft Surface Pro 9    	18     	$1,299.99   	$23,399.82
P106     	Dell XPS 13                	50     	$1,099.99   	$54,999.50
P107     	Apple iPad Air             	75     	$599.99     	$44,999.25
P108     	Fitbit Charge 5            	100    	$179.95     	$17,995.00
P109     	Amazon Echo Dot 5th Gen    	150    	$49.99      	$7,498.50
P110     	Sonos One SL               	80     	$199.99     	$15,999.20
P111     	Logitech MX Master 3       	120    	$99.99      	$11,998.80
P112     	HP Spectre x360            	25     	$1,499.99   	$37,499.75
P113     	GoPro Hero 11              	60     	$399.99     	$23,999.40
P114     	Nintendo Switch OLED       	45     	$349.99     	$15,749.55
P115     	Canon EOS R6               	15     	$2,499.99   	$37,499.85
P116     	Seagate 2TB External Hard Drive 200    	$69.99      	$13,998.00
P117     	Apple AirPods Pro 2nd Gen  	130    	$249.99     	$32,498.70
P118     	MSI GeForce RTX 4070       	40     	$599.99     	$23,999.60
P119     	Lenovo ThinkPad X1 Carbon  	20     	$1,799.99   	$35,999.80
P120     	Anker PowerCore 26800      	180    	$59.99      	$10,798.20
CURRENT CODE:
#!/bin/bash

# Function to display usage information
usage() {
	echo "Usage: invOpts -i | -n | -p | -h"
	echo "  -i  sort by product ID"
	echo "  -n  sort by product name"
	echo "  -p  sort by price"
	echo "  -h  display usage"
}

# Process command-line options using getopts
while getopts ":inp:h" opt; do
	case $opt in
    	i)
        	# Sort by product ID (Field 1) and save to a temp file
        	tempFile="/tmp/inventory_sorted_by_id_$$.txt"
        	sort -t: -k1,1 ~/A09/inventory > "$tempFile"
        	;;
    	n)
        	# Sort by product name (Field 2) and save to a temp file
        	tempFile="/tmp/inventory_sorted_by_name_$$.txt"
        	sort -t: -k2,2 ~/A09/inventory > "$tempFile"
        	;;
    	p)
        	# Sort by price (Field 4) and save to a temp file
        	tempFile="/tmp/inventory_sorted_by_price_$$.txt"
        	sort -t: -k4,4n ~/A09/inventory > "$tempFile"
        	;;
    	h)
        	# Display usage and exit
        	usage
        	exit 0
        	;;
    	?)
        	# Handle invalid options
        	echo "Invalid option: -$OPTARG"
        	usage
        	exit 1
        	;;
	esac
done

# If no option is provided, default to original file
if [[ -z $tempFile ]]; then
	tempFile=~/A09/inventory
fi

# Source the myFunctions script to use the chkFile function
source ~/Homework9/myFunctions

# Store the inventory file name
filename=~/A09/inventory

# Check if the file exists using chkFile
chkFile $filename
if [[ $? -ne 0 ]]; then
	echo "Error: Inventory file does not exist."
	exit 1
fi

# Print the header
printf "%-12s %-30s %-10s %-15s %-15s\n" "Product ID" "Product Name" "Quantity" "Price" "Total Value"
printf "%-12s %-30s %-10s %-15s %-15s\n" "-----------" "------------------------------" "--------" "-----" "-----------"

# Initialize total inventory value
totalInventoryValue=0

# Read the sorted file line by line (either sorted or original)
while IFS=: read -r productID productName quantity price; do
	# Calculate the total value: Quantity * Price
	totalValue=$(echo "$quantity * $price" | bc -l)

	# Format the price and total value with commas
	formattedPrice=$(echo $price | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')
	formattedTotalValue=$(echo $totalValue | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')

	# Print the formatted data
	printf "%-12s %-30s %-10s $%-14s $%-14s\n" "$productID" "$productName" "$quantity" "$formattedPrice" "$formattedTotalValue"

	# Add total value to the overall inventory value
	totalInventoryValue=$(echo "$totalInventoryValue + $totalValue" | bc -l)
done /,&/;ta')

# Print the total inventory value
printf "\nTotal Inventory Value: $%-14s\n" "$formattedTotalInventoryValue"

# Clean up the temporary file
rm -f "$tempFile"
Natasha Shorrock (5 rep)
Dec 10, 2024, 12:24 AM • Last activity: Jan 13, 2025, 09:59 AM
78 votes
5 answers
69976 views
getopt, getopts or manual parsing - what to use when I want to support both short and long options?
Currently I'm writing a Bash script which has the following requirements: * it should run on a wide variety of Unix/Linux platforms * it should support both short and (GNU) long options I know that `getopts` would be the preferred way in terms of portability but AFAIK it doesn't support long options...
Currently I'm writing a Bash script which has the following requirements: * it should run on a wide variety of Unix/Linux platforms * it should support both short and (GNU) long options I know that getopts would be the preferred way in terms of portability but AFAIK it doesn't support long options. getopt supports long options but the BashGuide recommends strongly against it: > Never use getopt(1). getopt cannot handle empty arguments strings, or > arguments with embedded whitespace. Please forget that it ever > existed. So, there still is the option of manual parsing. This is error-prone, produces quite some boilerplate code, and I need to handle errors by myself (I guess getopt(s) do error-handling by themselves). So, what would be the preferred choice in this case?
helpermethod (2052 rep)
Jan 29, 2013, 11:37 AM • Last activity: Aug 13, 2024, 01:54 PM
0 votes
1 answers
146 views
Manipulating arguments with OPTIND, OPTARG, getopts, and shift correctly
My small POSIX shell scripts do not usually take any arguments, so this is kind of new to me... The minimal snippet would probably look like this: ```sh # default for hotkey variable on top of script is set hotkey=Print ... while getopts ':hk:' option; do case "$option" in k) # override default hotk...
My small POSIX shell scripts do not usually take any arguments, so this is kind of new to me... The minimal snippet would probably look like this:
# default for hotkey variable on top of script is set
hotkey=Print
...
while getopts ':hk:' option; do

    case "$option" in

        k) # override default hotkey variable with supplied arg.
            hotkey=$OPTARG
            shift 2
        ;;
        h) # self-explanatory I assume, prints usage, and exits script with code 0
            print_usage_and_exit 0
        ;;
        *) # inspects unspecified arguments, prints usage, and exits script with code 1
            dump_args "$@"
            print_usage_and_exit 1
        ;;

    esac

done
...
What remains unclear to me, if in this particular case, there is any use for the notoriety known command:
shift $(( OPTIND - 1 ))
Thanks for any direction
Vlastimil Burián (30505 rep)
Jun 16, 2024, 04:10 PM • Last activity: Jul 23, 2024, 02:39 PM
8 votes
3 answers
4178 views
How to specify -? option with GNU getopt
When parsing command line arguments with GNU `getopt` command, how do I (if possible) do recognize `-?` as another option? Is there a way to escape it in the opstring?
When parsing command line arguments with GNU getopt command, how do I (if possible) do recognize -? as another option? Is there a way to escape it in the opstring?
Martín Schonaker (264 rep)
Jun 28, 2011, 01:14 AM • Last activity: Jun 19, 2024, 05:13 PM
26 votes
4 answers
53417 views
How do I handle switches in a shell script?
Are there some built-in tools that will recognize `-x` and `--xxxx` as switches (*flags* or "boolean options", rather than "ordinary arguments"), or do you have to go through all the arguments, test for dashes, and then parse the rest thereafter?
Are there some built-in tools that will recognize -x and --xxxx as switches (*flags* or "boolean options", rather than "ordinary arguments"), or do you have to go through all the arguments, test for dashes, and then parse the rest thereafter?
user394 (14722 rep)
Sep 18, 2011, 06:47 PM • Last activity: Jun 13, 2024, 09:31 AM
0 votes
1 answers
52 views
getopt with several `--`
I have a script with this usage: ``` myscript [options] positional-args... -- [fwd-params] ``` Because `[options]` can have long, or short variants, I like using `getopt`. But I'm having troubles. I use `getopt` like this: ``` args=$(getopt -o a:,b --long alpha:,gamma -- "$@") eval set -- "$args" wh...
I have a script with this usage:
myscript [options] positional-args... -- [fwd-params]
Because [options] can have long, or short variants, I like using getopt. But I'm having troubles. I use getopt like this:
args=$(getopt -o a:,b --long alpha:,gamma -- "$@")
eval set -- "$args"
while : ; do 
  case "$1" in
    -a | --alpha) a="$2" ; shift 2 ;; 
    -b          ) b=true ; shift   ;;
    --gamma     ) g=true ; shift   ;;
    -- )          shift  ; break   ;; 
  esac
done

positionals=()
while [ $# -gt 0 ] ; do
  case "$1" in
    *  ) positionals+=("$1"); shift ;;
    -- ) shift ; break ;;
  esac
done

# What-ever is left in "$@" needs to be forwarded to another program

backend "$@"
This works great if I don't have any [fwd-params]:
$ getopt -o a:,b -- -a 1 -b pos1 pos2
 -a '1' -b -- 'pos1' 'pos2'
            ^-- getopt adds this to help me find 
                the end-of-options/start-of-positionals
But it falls apart if the user defined any [fwd-params]. Here's my desired output:
$ getopt -o a:,b -- -a 1 -b pos1 pos2 -- fwd1
 -a '1' -b -- 'pos1' 'pos2' '--' 'fwd1'
                              ^
                              \-   I'll use this to delimit 
                                   the positional arguments 
                                   from the forwarding ones.
And here's what I actually get. The user's intentional -- has been filtered out.
$ getopt -o a:,b -- -a 1 -b pos1 pos2 -- fwd1
 -a '1' -b -- 'pos1' 'pos2' 'fwd1'
What's the best way to delimit my positional-arguments from the forwarding ones?
Stewart (15631 rep)
May 28, 2024, 03:40 PM • Last activity: May 28, 2024, 04:36 PM
3 votes
3 answers
6461 views
How to extract unknown arguments within a shell script?
I have a shell script that accepts a variety of options, some with arguments, some without, some short, some long. It should handle some of these options itself and pass on the rest it does not know how to care about to another program. Can I get `getopts` or something along its lines to store away...
I have a shell script that accepts a variety of options, some with arguments, some without, some short, some long. It should handle some of these options itself and pass on the rest it does not know how to care about to another program. Can I get getopts or something along its lines to store away unknown arguments? So for example, say my script is called program and should accept arguments - -n with a single argument, - --verbose without any argument and - -s without any argument. It parses and prints all its options and their arguments and then calls echo rest: with anything that remains. The following output should be observed. > program -sin42 --long --verbose -s -n with argument 42 --verbose rest: -i --long > program -n --short -n with argument --short > program -n error: -n without argument Can something like this be achieved in a shell script?
XZS (1488 rep)
Apr 28, 2015, 09:18 PM • Last activity: May 3, 2024, 04:40 PM
-1 votes
1 answers
268 views
pass all parameters to another sourced bash script that uses getopts
I am trying to pass all parameters from one script to another. However, there is an issue when the other script is sourced; all parameters are not passing correctly. **first.sh:** ``` #!/usr/bin/bash while getopts a option do case "${option}" in a) echo 'OptionA:somevalue';; esac done # This way wor...
I am trying to pass all parameters from one script to another. However, there is an issue when the other script is sourced; all parameters are not passing correctly. **first.sh:**
#!/usr/bin/bash


while getopts a option 
do 
    case "${option}"
    in
    a) echo 'OptionA:somevalue';; 
    esac 
done

# This way works
./second.sh "$@"

# Does not work when source command is used
#source ./second.sh "$@"
**second.sh:**
#!/usr/bin/bash


while getopts b:c option 
do 
    case "${option}"
    in
    b) echo 'OptionB:'"${OPTARG}";; 
    c) echo 'OptionC:somevalue';;
    esac 
done
**Output:**
$ ./test.sh -a -b foo -c
OptionA:somevalue
./first.sh: illegal option -- b
./second.sh: illegal option -- a
OptionB:foo
OptionC:somevalue
**Expected output:**
$ ./test.sh -a -b foo -c
OptionA:somevalue
OptionB:foo
OptionC:somevalue
**What to achieve?** Passing the parameters correctly to second.sh with source command, getting rid of illegal option and compatibility with other shells. Edit: Updated the question again with more clear examples.
Zero (39 rep)
Mar 9, 2024, 03:58 PM • Last activity: Mar 20, 2024, 08:44 AM
2 votes
1 answers
251 views
script arguments in bash
I am working on a a script that need to take two script arguments and use them as variables in the script. I couldn't get this working and unable to find out what I am doing wrong. I see the issue is the second argument, as I see in some of my tests(as mentioned in the bottom of this post) it is not...
I am working on a a script that need to take two script arguments and use them as variables in the script. I couldn't get this working and unable to find out what I am doing wrong. I see the issue is the second argument, as I see in some of my tests(as mentioned in the bottom of this post) it is not being read. Here is the code: #!usr/bin/bash help() { echo "" echo "Usage: $0 -p patch_level -e environment" echo -e "\t-p Patch level that you are tryin to update the server" echo -e "\t-e Environment that the patch need to be run on" exit 1 # Exit script after printing help } while getopts "p:e" opt do case "${opt}" in p ) patch_level="$OPTARG" ;; e ) _env="$OPTARG" ;; ? ) help ;; # Print help in case parameter is non-existent esac done if [ -z "$patch_level" ] || [ -z "$_env" ]; # checking for null parameter then echo "Some or all of the parameters are empty"; help else echo "$patch_level and $_env" fi When I run the script like below , I get this. > ./restart.sh -p 2021 -e sbx > Some or all of the parameters are empty > Usage: ./restart.sh -p patch_level -e environment > -p Patch level that you are tryin to update the server > -e Environment that the patch need to be run on Note: I modeled my code based on the third answer in this https://unix.stackexchange.com/questions/31414/how-can-i-pass-a-command-line-argument-into-a-shell-script I see the issue is with the second variable (-e). Because if I change the last if statement from "or to and", the script runs but doesn't print anything for the second variable: here is what I am talking about if [ -z "$patch_level" ] && [ -z "$_env" ]; the output is ./restart.sh -p 2021 -e sbx 2021 and This server will be patched to 2021 I am on Ubuntu if that matters.
MO12 (409 rep)
Jan 28, 2024, 08:43 PM • Last activity: Jan 29, 2024, 03:59 PM
-2 votes
1 answers
955 views
Bash getopts error handling
This is an error I encountered when playing with Getopts. The following is the code snippet I have been playing simply listen to 3 options when executing a script. while getopts "vcn" opt; do case $opt in v) echo "Print V" ;; c) echo "Print C" ;; n) echo "Print N" ;; *) echo "Invalid Option" && exit...
This is an error I encountered when playing with Getopts. The following is the code snippet I have been playing simply listen to 3 options when executing a script. while getopts "vcn" opt; do case $opt in v) echo "Print V" ;; c) echo "Print C" ;; n) echo "Print N" ;; *) echo "Invalid Option" && exit 1 ;; esac done I'm not sure Why I'm getting the below error when executing this script even though I have handled errors with *) option to do so. The error handle is working as shown in the picture below but after getting an unprogrammed error. The Error msg on the terminal
Dettlaff404 (3 rep)
Jan 7, 2024, 11:47 AM • Last activity: Jan 7, 2024, 07:21 PM
4 votes
2 answers
16854 views
Handling long-options with getopts
I am parsing options with `getopts` but would like to handle long-options as well. print-args () { title="$1" ; shift printf "\n%s\n" "${title}: \$@:" for arg in "$@"; do (( i = i + 1 )) printf "%s |%s|\n" "${i}." "$arg" done } getopts_test () { aggr=() for arg in "$@"; do case $arg in ("--colour"|"...
I am parsing options with getopts but would like to handle long-options as well. print-args () { title="$1" ; shift printf "\n%s\n" "${title}: \$@:" for arg in "$@"; do (( i = i + 1 )) printf "%s |%s|\n" "${i}." "$arg" done } getopts_test () { aggr=() for arg in "$@"; do case $arg in ("--colour"|"--color") aggr+=( "-c" ) ;; ("--colour="*|"--color="*) aggr+=( "-c" "${arg#*=}" ) ;; (*) aggr+=( "$arg" ) ;; esac done print-args "print" "$@" eval set -- "${aggr[@]}" print-args "eval" "$@" set -- "${aggr[@]}" print-args "set" "$@" local OPTIND OPTARG local shortopts="C:" while getopts "$shortopts" arg; do case $arg in ("c") context="$OPTARG" ;; (*) break ;; esac done shift $(( OPTIND - 1 )) } But I wonder whether the use of set -- "${aggr[@]}" is correct. Or is the following (using eval) more appropriate? eval set -- "${aggr[@]}" I have performed a test shown below. With eval, the string "Gunga Din" is split up, whereas with set -- "${aggr[@]}", it is being parsed correctly as a single string. getopts_test -f -g 130 --colour="170 20" "Gunga Din" print: $@: 1. |-f| 2. |-g| 3. |130| 4. |--colour=170 20| 5. |Gunga Din| eval: $@: 1. |-f| 2. |-g| 3. |130| 4. |-c| 5. |170| 6. |20| 7. |Gunga| 8. |Din| set: $@: 1. |-f| 2. |-g| 3. |130| 4. |-c| 5. |170 20| 6. |Gunga Din| Then I ran another function that uses the non-GNU getopt. getopt_test () { shortopts="Vuhv::H::w::e::n::l::C:" shortopts="${shortopts}bgcrmo" longopts="version,usage,help,verbosity::" longopts="${longopts},heading::,warning::,error::" longopts="${longopts},blu,grn,cyn,red,mgn,org" opts=$( getopt -o "$shortopts" -l "$longopts" -n "${0##*/}" -- "$@" ) print-args "\$@:" "$@" print-args "opts:" "$opts" set -- "$opts" print-args "set -- \"$opts\"" "$@" eval set -- "$opts" print-args "eval set -- \"$opts\"" "$@" } This resulted in the following getopt_test --warning=3 "foo'bar" "Gunga Din" $@: 1. |--warning=3| 2. |foo'bar| 3. |Gunga Din| opts: 1. | --warning '3' -- 'foo'\''bar' 'Gunga Din'| set -- "$opts" 1. | --warning '3' -- 'foo'\''bar' 'Gunga Din'| eval set -- "$opts" 1. |--warning| 2. |3| 3. |--| 4. |foo'bar| 5. |Gunga Din| As shown the result of getopt is a single entry with positional arguments re-arranged. This shows the need to use eval set -- "$opts" to split the positional arguments in the opts string into five entries for option parsing and processing.
Vera (1363 rep)
Oct 30, 2021, 09:46 AM • Last activity: Dec 18, 2023, 04:43 PM
2 votes
1 answers
1443 views
getopts does not match the second argument
I'm trying to get a script to: * set a variable with `-q` option * show help for `-h` option, and * fail for other options `-*`, but allow positional arguments Here is the `getopts` snippet I'm using: while getopts qh opt; do case "${opt}" in q) quiet="true" ;; h) usage exit 1 ;; \?) echo "unrecogni...
I'm trying to get a script to: * set a variable with -q option * show help for -h option, and * fail for other options -*, but allow positional arguments Here is the getopts snippet I'm using: while getopts qh opt; do case "${opt}" in q) quiet="true" ;; h) usage exit 1 ;; \?) echo "unrecognized option -- ${OPTARG}" exit 1 ;; esac shift done echo "unparsed: $*" This seems pretty straightforward. However it only works if I provide a single argument (a.sh -q or a.sh -h do what's expected). However, it does not do anything if I provide both arguments, or provide an unrecognized argument as at $2: $ ./a.sh -b unrecognized option -- b $ ./a.sh -q -b unparsed: -b $ ./a.sh -h -k this is my help message unparsed: -k Any ideas why the second argument ($2) is not handled in the getopts loop?
ahmet alp balkan (741 rep)
Oct 8, 2017, 05:11 AM • Last activity: Dec 18, 2023, 09:25 AM
2 votes
1 answers
364 views
How bash getopts knows what arguments the call has
If `getopts` is a bash function, by my understanding, you need to pass `$@` - the whole arguments to `getopts` to let the function know what kind of arguments you have in order to proceed, right? It seems to me that you don't need it, so how the `getopts` get to know what arguments I have in the cur...
If getopts is a bash function, by my understanding, you need to pass $@ - the whole arguments to getopts to let the function know what kind of arguments you have in order to proceed, right? It seems to me that you don't need it, so how the getopts get to know what arguments I have in the current scope? Does it have a way to trace the previous call like the other high-level languages do?
while getopts abcde opt; do
              ˄˄˄˄˄ <-- you only need to pass the argument labels here, 
                        how getopts knows what arguments I have
    case $opt in
        ...
    esac
done
Till (193 rep)
Nov 21, 2023, 08:08 AM • Last activity: Nov 25, 2023, 04:04 PM
3 votes
2 answers
3627 views
Can getopts arguments be combined with other input?
I am writing a script that would take a string as input along with other options the user can select by using arguments as indicators. So in other words, something like this: ./script "My input string" -pxz or ./script -pxz "My input string" But I run into the following issue. It seems the getopts c...
I am writing a script that would take a string as input along with other options the user can select by using arguments as indicators. So in other words, something like this: ./script "My input string" -pxz or ./script -pxz "My input string" But I run into the following issue. It seems the getopts command stops working after a non-getopts-style argument is entered. Check this out, for example: #!/bin/bash while getopts "ab" arg; do echo $arg received done When we run it we get: $ ./example.sh -a -b -a string -b a received b received a received $ It stops at "string" and won't continue. The getopts command returns a nonzero exit status because "string" is not the kind of argument it expects to read, and the while loop ends. I've tried adding a second while getopts but that doesn't do anything. The "read head" of getopts is still stuck on that "string" argument and will simply exit with a nonzero exit status again. What this means is that seemingly, I wouldn't be able to have the user enter their string first and then the options, because getopts would never be able to read past the string and get there. So I can't do this: ./script "My input string" -pxz On the other hand, if I told the user to enter first their options and then the string I'd have the problem of figuring out how to retrieve the string. Normally, if there were no options, I'd do this: string="$1" But now since there are options and I don't know how many there are, I no longer know what position the string occupies. So how would I be able to retrieve it? Now, ideally my script should actually be able to work in both of those ways or even a combination of the two. It should be able to handle input like: ./script -p "My input string" -xz So how can I go about resolving this issue?
Isaac D. Cohen (243 rep)
Aug 9, 2022, 09:02 PM • Last activity: Nov 1, 2023, 05:20 PM
-1 votes
1 answers
364 views
how to exit immediately with getopts option in bash script
what I tried. ~~~sh #!/bin/bash # set -e echo hello while getopts sr o; do case $o in s) echo "no" yell() { echo "$0: $*" >&2; } die() { yell "$*"; exit 111; } try() { "$@" || die "cannot $*"; } ;; r) echo "yes" yell() { echo "$0: $*" >&2; } die() { yell "$*"; exit 111; } try() { "$@" || die "cannot...
what I tried. ~~~sh #!/bin/bash # set -e echo hello while getopts sr o; do case $o in s) echo "no" yell() { echo "$0: $*" >&2; } die() { yell "$*"; exit 111; } try() { "$@" || die "cannot $*"; } ;; r) echo "yes" yell() { echo "$0: $*" >&2; } die() { yell "$*"; exit 111; } try() { "$@" || die "cannot $*"; } ;; \?) exit 3;; #invalid option esac done echo after_case ~~~ What I am trying to do: in terminal, the following 2 command: bash /home/jian/Desktop/pgdev/test1.sh -s bash /home/jian/Desktop/pgdev/test1.sh -r do not print out aftercase. references: https://unix.stackexchange.com/questions/684717/how-to-use-getopts-in-bash https://stackoverflow.com/questions/1378274/in-a-bash-script-how-can-i-exit-the-entire-script-if-a-certain-condition-occurs
jian (597 rep)
Oct 12, 2023, 05:02 PM • Last activity: Oct 13, 2023, 03:22 AM
1 votes
1 answers
1672 views
What does colon (:) mean for getopts?
I am trying to parse options for my script with `getopts` and I decided that it would be best to read up on it in the POSIX standard, as it's usually extremely helpful. The [*DESCRIPTION* section][1] is fairly ambiguous in regard to the use of colon (:) in *optstring*, so I looked up how people use...
I am trying to parse options for my script with getopts and I decided that it would be best to read up on it in the POSIX standard, as it's usually extremely helpful. The *DESCRIPTION* section is fairly ambiguous in regard to the use of colon (:) in *optstring*, so I looked up how people use : with getopts on the internet and now I'm confused. What does colon do in commands like getopts abc:d name and how am I supposed to know just by reading the standard?
Nicolas Dumitru (121 rep)
Aug 22, 2023, 04:06 PM • Last activity: Aug 22, 2023, 04:44 PM
0 votes
0 answers
58 views
Is there a tool or macro processor capable of compactly expressing BASH CLI interfaces?
I am writing scripts with the following boilerplate CLI pattern: ``` usage(){ echo "$0 yada yada" ... echo } for arg in "$@"; do case "$arg" in '--help|-help') set -- "$@" '-h';; ... esac done OPTIND=1 while getopts 'h...' opt; do case "$opt" in 'h') usage; exit 0;; ... esac done shift $((OPTIND-1))...
I am writing scripts with the following boilerplate CLI pattern:
usage(){
  echo "$0 yada yada"
  ...
  echo 
}
for arg in "$@"; do
  case "$arg" in
    '--help|-help') set -- "$@" '-h';;
    ...
  esac
done

OPTIND=1
while getopts 'h...' opt; do
  case "$opt" in
     'h') usage; exit 0;;
      ...
  esac
done
shift $((OPTIND-1))
Is there any way to compress or encapsulate this in BASH on linux with other tools, perhaps an additional dependency?
Chris (1075 rep)
Jul 25, 2023, 03:37 PM
0 votes
1 answers
244 views
Multichar options in Unix sysytems
I have a usecase wherein I need to support multiple character option. Currently I am using single character option for getopts. Multi-character option is desirable.What's the best way of doing this? I came across articles implementing a manual parser for this usecase,but is that optimal with respect...
I have a usecase wherein I need to support multiple character option. Currently I am using single character option for getopts. Multi-character option is desirable.What's the best way of doing this? I came across articles implementing a manual parser for this usecase,but is that optimal with respect to performance. I want something like -ab to be treated as -ab only and not -a -b . Also is it a good coding practice? This is just done to make the options more meaningful as opposed to single char options which do not provide complete information about that option. Important: I also want optargs with these multi-character options .Example -ab "sdfd" . Here's the code
while getopts ":s:p:q:j:o" opt; do
  case ${opt} in
    s)
      only_save=TRUE
      new_tok=$OPTARG
      ;;
    p)
      only_upload_enum_json=TRUE
      enum="job_status"
      new_tok=$OPTARG
      ;;
    q)
      only_upload_enum_json=TRUE
      enum="lifecycle_state"
      new_tok=$OPTARG
      ;;
    j)
      only_download_enum_json=TRUE
      enum=$OPTARG
      ;;
    o)
      only_download=TRUE
      ;;
    \?)
      echo "   -s "
      echo "   -p "
      echo "   -q "
      echo "   -j "
      echo "   -o "
      exit;
      ;;
  esac
done
Here for job_status its desirable to use -js instead of -p to make it more meaningful.and similarly for lifecycle_state
Vatsal A Mehta (101 rep)
Jun 30, 2023, 12:13 PM • Last activity: Jun 30, 2023, 02:10 PM
-1 votes
1 answers
557 views
How to check for passed options using getopts in a POSIX shell? (Report, count, and discard.)
How to check for passed options using [`getopts` (man page)][1] in a POSIX shell? (Report, count, and discard.) My idea is this: Many of my scripts take no options (not even `-h` for help, I am transitioning to `help` directly. And so, if any number of options (switches) is given, I want to count th...
How to check for passed options using getopts (man page) in a POSIX shell? (Report, count, and discard.) My idea is this: Many of my scripts take no options (not even -h for help, I am transitioning to help directly. And so, if any number of options (switches) is given, I want to count them, report them, and simply discard them (Don't do any action on them). Let's include all 0-9, and both lower and upper a-z (A-Z). --- **Update:** Many of my scripts do not take even files as arguments, and that is the case with this script. --- **Usage** help looks like this:
usage ()
{
cat << EOF
MPV video player subtitles enable/disable toggling
--------------------------------------------------
on              Enable  subtitles toggling in MPV.
off             Disable subtitles toggling in MPV.
help            Print this help message.
version         Print the script version.
EOF
}
Vlastimil Buri&#225;n (30505 rep)
Jun 20, 2023, 03:13 AM • Last activity: Jun 20, 2023, 12:45 PM
Showing page 1 of 20 total questions