Could You Please Share This Post? I Appreciate It And Thank YOU! :) Have A Nice Day!
4.6
(219)

What is Bash?

Bash is basically the modern layer to use of sh. (Bash Arguments Parsing) As we can read on official page bash is described as: “It offers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification.”

  • command-line editing,
  • unlimited size command history,
  • job control,
  • shell functions and aliases,
  • indexed arrays of unlimited size,
  • integer arithmetic in any base from two to sixty-four.

Bash Parse input arguments (Bash Space-Separated)

We very often want to run a bash script with input arguments. The question often arises how to do it in an appropriate, clean and transparent way, the so-called production and which will be easy to change or develop in the future. And it will definitely happen 🙂

Let’s take the example of running a script and passing two parameters to it. Suppose we want to specify the name of the environment (-e) and the number of iterations (-i) of some code execution inside the script:

./test-script.sh -e DEV -i 10

Then inside the test-script.sh we can parse it using the following code:

usage() {
  echo "Usage: $0 [option...]" >&2
  echo "   -e     env"
  echo "   -i     iterations"
  exit 1
}

while getopts ":e:i:" o; do
  case "${o}" in
  e)
    ENV=${OPTARG}
    ;;
  i)
    ITERATIONS=${OPTARG}
    ;;
  *)
    usage
    ;;
  esac
done
shift $((OPTIND - 1))

Bash Function With Parameters

We very often want to create a function with parameters. But it is not as obvious as in other programming languages where parameters are passed in parentheses. We have to get to them covertly. The function call looks like:

someFunction "$ENV" "$ITERATIONS"

The function is implemented as follows:

someFunction() {

  environment=$1
  iterations=$2

  ...

}

For the next parameters, we refer to the $ and its number, starting from 1.

That’s all about topic: Bash Parse input arguments and functions with parameters!

Could You Please Share This Post? 
I appreciate It And Thank YOU! :)
Have A Nice Day!

BigData-ETL: image 7YOU MIGHT ALSO LIKE

How useful was this post?

Click on a star to rate it!

Average rating 4.6 / 5. Vote count: 219

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?