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
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.
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 …
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With