Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass two parameters or arguments in bash scripting [duplicate]

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

like image 891
user1983063 Avatar asked Aug 15 '14 09:08

user1983063


People also ask

How do I pass multiple arguments to a bash script?

You can pass more than one argument to your bash script. In general, here is the syntax of passing multiple arguments to any bash script: script.sh arg1 arg2 arg3 … The second argument will be referenced by the $2 variable, the third argument is referenced by $3 , .. etc.

How do I pass multiple values to a single argument in shell script?

To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 … To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 …

What is Echo $$ in bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.


1 Answers

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
like image 54
konsolebox Avatar answered Sep 24 '22 09:09

konsolebox