7

I am new to bash scripting and I need your support to solve this problem. I have a bash script "start.sh". I want to write a script with two arguments so that I could run the script in the following way

./start.sh -dayoffset 1 -processMode true

dayoffset and processMode are the two parameters that I have to script.

dayoffset = 1 is the reporting date (today) processMode = true or false

user1983063
  • 139
  • 1
  • 2
  • 10

1 Answers1

13

As a start you can do this:

#!/bin/bash
dayoffset=$1
processMode=$2
echo "Do something with $dayoffset and $processMode."

Usage:

./start.sh 1 true

Another:

#!/bin/bash

while [[ $# -gt 0 ]]; do
    case "$1" in
    -dayoffset)
        day_offset=$2
        shift
        ;;
    -processMode)
        if [[ $2 != true && $2 != false ]]; then
            echo "Option argument to '-processMode' can only be 'true' or 'false'."
            exit 1
        fi
        process_mode=$2
        shift
        ;;
    *)
        echo "Invalid argument: $1"
        exit 1
    esac
    shift
done

echo "Do something with $day_offset and $process_mode."

Usage:

./start.sh -dayoffset 1 -processMode true

Example argument parsing with day offset:

#!/bin/bash 
dayoffset=$1
date -d "now + $dayoffset days"

Test:

$ bash script.sh 0
Fri Aug 15 09:44:42 UTC 2014
$ bash script.sh 5
Wed Aug 20 09:44:43 UTC 2014
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • Hi, thanks of the reply. My script is more or less like this. Does it make any sense. `code` if [ $# -eq 3 ]; then if [ -z "$1" ]; then DAY_OFFSET="-1" else DAY_OFFSET="$1" fi if [ -n "$2" ] && [ $2 = "repeat" ]; then echo "Wiederholungslauf" PARAMETERS="${PARAMETERS} -processMode true" else echo "Default" PARAMETERS="${PARAMETERS} -processMode false" fi else echo "Wrong count of paramaeters given" batch_exit fi `code` – user1983063 Aug 15 '14 at 09:40
  • 1
    @user1983063 Your version is not too dynamic. I suggest you use the general form I gave. I actually prefer all-caps variable names so can you just change those variables to all-caps forms. Just be careful on using builtin shell variables.... And you're welcome :) – konsolebox Aug 15 '14 at 09:54