Home > Enterprise >  Looping through input variables and printing in shell script
Looping through input variables and printing in shell script

Time:09-17

Hi pls I'm new to shell scripting. I need to write a shell script that will ask for 2 parameters, one for startdate and another for number of days.

Then loop from start date to number of days and print each date. E.g 16-09-2022 and 4 will print: 16-09-2022 17-09-2022 18-09-2022 19-09-2022

Tried this:

#! /bin/bash

echo "enter date"
read var1

echo "enter no of days"
read var2

for i in {0..$var2..1}
do
 echo $i $var1   
(here's where I'm trying to figure how to increment the dates)
done

Thanks

CodePudding user response:

Try the following:

Save the script below in file, name it e.g. get-started-with-bash-by-example.sh and run it as follows:

bash get-started-with-bash-by-example.sh 2022-09-25 10
#!/bin/bash

# USAGE:
# ${SCRIPT_NAME} args
#       arg1 - date (must be in format 'yyyy-mm-dd')
#       arg2 - number of days to add
# 
# EXAMPLES
#    ${SCRIPT_NAME} 2022-09-25 10

for i in $(seq "$2")
do
    date  %d-%m-%Y -d "$1   $i day"
done

Or with user input:

#!/bin/bash

read -p "Enter start-date in 'yyyy-mm-dd' format: " startdate
read -p "Enter number of days to add: " nofdaystoadd

for i in $(seq "$nofdaystoadd")
do
    date  %d-%m-%Y -d "$startdate   $i day"
done

OUTPUT:

26-09-2022
27-09-2022
28-09-2022
29-09-2022
30-09-2022
01-10-2022
02-10-2022
03-10-2022
04-10-2022
05-10-2022

I hope this example helps you to get started with bash.

  • Related