savannah-cvs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Savannah-cvs] [717] make option parsing complete, make code snippet sec


From: iank
Subject: [Savannah-cvs] [717] make option parsing complete, make code snippet section
Date: Wed, 13 Dec 2023 16:52:53 -0500 (EST)

Revision: 717
          
http://svn.savannah.gnu.org/viewvc/?view=rev&root=administration&revision=717
Author:   iank
Date:     2023-12-13 16:52:51 -0500 (Wed, 13 Dec 2023)
Log Message:
-----------
make option parsing complete, make code snippet section

Modified Paths:
--------------
    trunk/sviki/fsf/bash-style-guide.mdwn

Modified: trunk/sviki/fsf/bash-style-guide.mdwn
===================================================================
--- trunk/sviki/fsf/bash-style-guide.mdwn       2023-12-13 21:40:28 UTC (rev 
716)
+++ trunk/sviki/fsf/bash-style-guide.mdwn       2023-12-13 21:52:51 UTC (rev 
717)
@@ -181,12 +181,6 @@
 done
 ```
 
-To work from the same directory of the script
-
-```
-readonly this_file="$(readlink -f -- "${BASH_SOURCE[0]}")"; cd ${this_file%/*}
-```
-
 Variables:
 
 Environment variables are all caps. Other vars are lowercase. Underscore
@@ -445,12 +439,13 @@
 ```
 usage() {
     cat <<EOF
-Usage: ${0##*/} [OPTIONS] ARG1
+Usage: ${0##*/} [OPTIONS] ARG1 ARG2
 One line description
 
+-b                    Set this boolean option.
+-l|--long-opt OPTION  Set this this long option.
+-h|--help             Print help and exit.
 
--h|--help  Print help and exit.
-
 Note: Uses GNU getopt options parsing style
 EOF
   exit $1
@@ -460,12 +455,12 @@
 
 bool_opt=false # default
 long_opt=foo # default
-temp=$(getopt -l help,long-opt: hso: "$@") || usage 1
+temp=$(getopt -l help,long-opt: hbl: "$@") || usage 1
 eval set -- "$temp"
 while true; do
     case $1 in
-        -s) bool_opt=true; shift ;;
-        -o|--long-opt) long_opt="$2"; shift 2 ;;
+        -b) bool_opt=true; shift ;;
+        -l|--long-opt) long_opt="$2"; shift 2 ;;
         -h|--help) usage ;;
         --) shift; break ;;
         *) echo "$0: Internal error! unexpected args: $*" ; exit 1 ;;
@@ -472,10 +467,35 @@
     esac
 done
 read arg1 arg2 <<<"$@"
+if (( $# != 2 )); then
+  echo "$0: error: expected 2 options, got $#." >&2
+  exit 1
+fi
 
 ##### end command line parsing ########
 ```
 
+# Very common code snippets
+
+To work from the same directory of the script:
+
+```
+readonly this_file="$(readlink -f -- "${BASH_SOURCE[0]}")"; cd ${this_file%/*}
+```
+
+Print script name & command, then execute command:
+
+```
+m() { printf "${0##*/}: %s\n"  "$*"; "$@"; }
+``
+
+
+Make sure the script is run as root:
+
+```
+[[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
+```
+
 # License
 
 Copying and distribution of this file, with or without modification,




reply via email to

[Prev in Thread] Current Thread [Next in Thread]