How to pass two parameters or arguments in a bash script

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 can run the script as follows

./start.sh -dayoffset 1 -processMode true

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

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

+5
source share
1 answer

In the beginning you can do this:

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

Using:

 ./start.sh 1 true 

Other:

 #!/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." 

Using:

 ./start.sh -dayoffset 1 -processMode true 

An example of parsing arguments with a daily 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 
+8
source

Source: https://habr.com/ru/post/1200396/


All Articles