Snippets

Víctor Goñi Sanz Bash tutorial 2 - Usage

Updated by Víctor Goñi Sanz

File mySecondScript.sh Modified

  • Ignore whitespace
  • Hide word diff
-#!/bin/bash 
-
+#!/bin/bash
 # Check spell http://www.shellcheck.net/# online, or download, to test!
 
-# Bash have variable when call an executable, $0 = CommandName, $1..$N = Arguments
-argumentsLimit=1
-commandName=$(basename "$0") 
-commandPath=${0%/*}
-argumentsRequired="first second"
-
-###### Function declaration
-# My first function, display usage info
-f_display_usage() 
-{ 
-	echo "This script require arguments!" 
-	echo -e "\nUsage:\n$0 [${argumentsRequired}] \n" 
-} 
-# My second function, check if
-f_check_correct_parameters()
+############################################################ Function declaration
+### OPTIONS
+# This function, display usage info
+f_display_usage()
+{
+  echo -e "\n--------------------------------------------------"
+	echo "|  This function teach you how this script works"
+	echo -e "|  Usage:\n|  $0"  # -e option allow use \n
+  echo "|  ${optionHelp} = Print usage"
+  echo "|  ${optionSay} = Print echo with message"
+  echo "|  ${optionPrintOptions} = Print all options"
+  echo "|  ${optionAuthor} = Print author's name"
+  echo -e "--------------------------------------------------"
+}
+f_say()
+{
+  echo -e "\n--------------------------------------------------"
+  echo "  I want to say: ${1}"
+  echo -e "--------------------------------------------------"
+}
+f_author()
+{
+  echo -e "\n--------------------------------------------------"
+  echo "  The author is: vgoni"
+  echo -e "--------------------------------------------------"
+}
+f_options()
 {
-# if less than ${argumentsLimit} arguments supplied, display usage 
-	if [  $# -le ${argumentsLimit} ] 
-	then 
-		display_usage
-		exit 1
-	fi 
+  echo -e "\n--------------------------------------------------"
+  echo "  Printing arguments..."
+  echo "  The number of arguments provided is: ${Nargs}"
+  for ((i=0; i < ${Nargs}; i++))
+  {
+     echo "  The argument $((i+1)): ${args[$i]}"
+  }
+  echo "  No more arguments!"
+  echo -e "--------------------------------------------------"
 }
-f_main()
+### Other functions
+# Check if are provided correct arguments
+f_evaluate_options()
 {
+  echo "  Evaluation options, number of arguments: ${Nargs}"
+  eval set -- ${options}
+  echo "  Options: ${options}"
+}
+############################################################ End Function declaration
+
+# Main program
+clear   # clear terminal
+
+# First of all, store arguments in a variable.
+# Bash have variable when call an executable, $0 = CommandName, $1..$N = Arguments
+# We store arguments in an array. If a function is called, you cannot access to them if not are global variables
+# because they are overwrited by function arguments.
+args=(${@}) # Arguments
+Nargs=(${#})  # Number of arguments
+
+# We define options, using getopt
+# -o Each single character stands for an option
+# -l Long name for each option
+# : after an option (short or long) tells that option is required argument
+# :: tells is a optional argument
+# For extension take a look here: http://www.bahmanm.com/blogs/command-line-options-how-to-parse-in-bash-using-getopt
+options=$(getopt -o hs:ao -l help,say:,author,options -- "${@}")
+if [[ $? -ne 0 ]]
+then
+  echo "  Error: Detected invalid option"
+fi
+# -o hs:ao = h & a option, no arguments; s option with a required option;
+# -l help,say:,author = same.
+# Declarate variables with options to clarify
+optionHelp="-h|--help"
+optionSay="-s|--say"
+optionAuthor="-a|--author"
+optionPrintOptions="-o|--options"
+
+# We define some global variables
+commandName=$(basename "$0")        # Extract name from first variable
+commandPath=$(pwd)                  # Get the path with command pwd
+
 echo "------- My second script begins execution..."
 echo "--------------------------------------------"
-echo "   Executing command: ${commandName}" 
+echo "   Executing command: ${commandName}"
 echo "   At path: ${commandPath}"
-echo "   You want to have ${argumentsLimit} and provide ${#}"
- 
-f_check_correct_parameters
- 
-# check whether user had supplied -h or --help . If yes display usage 
-	if [[ ( $# == "--help") ||  $# == "-h" ]] 
-	then 
-		display_usage
-		exit 0
-	fi 
+
+# Call a function to evaluate arguments as options
+f_evaluate_options
+
+# Check all arguments
+# We are going to check the all the options shifting them.
+# Using shift, the positional parameters are shifted to the left by this number, N.
+# Using case syntaxis, more info: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html
+while [ "$1" != "" ]
+do
+  echo "Processing option: ${1}"
+  case "$1" in
+      -h|--help) f_display_usage ;; # Call function
+      -s|--say) f_say $2 ; shift ;; # Call function with argument, and discard argument
+      -a|--author) f_author ;;      # Call a function to print author
+      -o|--options) f_options ;;     # Call a function to print options
+      *)         echo "Unknown option: $1" ; f_display_usage ; break ;;
+  esac
+  shift;  # Advance
+done;
 
 echo "------- My second script end now!"
 echo "---------------------------------"
-}
-###### End Function declaration
-
-# Call main
-f_main
Updated by Víctor Goñi Sanz

File mySecondScript.sh Modified

  • Ignore whitespace
  • Hide word diff
 #!/bin/bash 
 
+# Check spell http://www.shellcheck.net/# online, or download, to test!
+
 # Bash have variable when call an executable, $0 = CommandName, $1..$N = Arguments
 argumentsLimit=1
 commandName=$(basename "$0") 
Updated by Víctor Goñi Sanz

File mySecondScript.sh Modified

  • Ignore whitespace
  • Hide word diff
 # Bash have variable when call an executable, $0 = CommandName, $1..$N = Arguments
 argumentsLimit=1
 commandName=$(basename "$0") 
+commandPath=${0%/*}
 argumentsRequired="first second"
 
-display_usage() 
+###### Function declaration
+# My first function, display usage info
+f_display_usage() 
 { 
 	echo "This script require arguments!" 
 	echo -e "\nUsage:\n$0 [${argumentsRequired}] \n" 
 } 
-
-# 
-echo "   Executing command: ${commandName}" 
-
-echo "   You want to have ${argumentsLimit} and provide ${#}"
- 
-# if less than two arguments supplied, display usage 
+# My second function, check if
+f_check_correct_parameters()
+{
+# if less than ${argumentsLimit} arguments supplied, display usage 
 	if [  $# -le ${argumentsLimit} ] 
 	then 
 		display_usage
 		exit 1
 	fi 
+}
+f_main()
+{
+echo "------- My second script begins execution..."
+echo "--------------------------------------------"
+echo "   Executing command: ${commandName}" 
+echo "   At path: ${commandPath}"
+echo "   You want to have ${argumentsLimit} and provide ${#}"
+ 
+f_check_correct_parameters
  
 # check whether user had supplied -h or --help . If yes display usage 
 	if [[ ( $# == "--help") ||  $# == "-h" ]] 
 		display_usage
 		exit 0
 	fi 
- 
-# display usage if the script is not run as root user 
-	if [[ $USER != "root" ]]; then 
-		echo "This script must be run as root!" 
-		exit 1
-	fi 
- 
-echo "All good !!!"
+
+echo "------- My second script end now!"
+echo "---------------------------------"
+}
+###### End Function declaration
+
+# Call main
+f_main
Updated by Víctor Goñi Sanz

File mySecondScript.sh Modified

  • Ignore whitespace
  • Hide word diff
 echo "   You want to have ${argumentsLimit} and provide ${#}"
  
 # if less than two arguments supplied, display usage 
-	if [  $# -le ${ArgumentsLimit} ] 
+	if [  $# -le ${argumentsLimit} ] 
 	then 
 		display_usage
 		exit 1
Created by Víctor Goñi Sanz

File mySecondScript.sh Added

  • Ignore whitespace
  • Hide word diff
+#!/bin/bash 
+
+# Bash have variable when call an executable, $0 = CommandName, $1..$N = Arguments
+argumentsLimit=1
+commandName=$(basename "$0") 
+argumentsRequired="first second"
+
+display_usage() 
+{ 
+	echo "This script require arguments!" 
+	echo -e "\nUsage:\n$0 [${argumentsRequired}] \n" 
+} 
+
+# 
+echo "   Executing command: ${commandName}" 
+
+echo "   You want to have ${argumentsLimit} and provide ${#}"
+ 
+# if less than two arguments supplied, display usage 
+	if [  $# -le ${ArgumentsLimit} ] 
+	then 
+		display_usage
+		exit 1
+	fi 
+ 
+# check whether user had supplied -h or --help . If yes display usage 
+	if [[ ( $# == "--help") ||  $# == "-h" ]] 
+	then 
+		display_usage
+		exit 0
+	fi 
+ 
+# display usage if the script is not run as root user 
+	if [[ $USER != "root" ]]; then 
+		echo "This script must be run as root!" 
+		exit 1
+	fi 
+ 
+echo "All good !!!"
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.