0

I am pretty new to bash scripting. I have my bash script below and I want to include an if statement when month (ij==09) equals 09 then "i" should be from 01 to 30. I tried several ways but did not work.

How can I include an if statement in the code below to achieve my task.? Any help is appreciated.

Thanks.

#!/bin/bash
        for ii in 2007 
        do
        for i in 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #Day of the Month
        do
        for ij in 09 10 # Month
        do
         for j in 0000 0100 0200 0300 0400 0500 0600 0700 0800 0900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000 2100 2200 2300
         do
         cdo cat DAS_0125_H.A${ii}${ij}${i}.${j}.002_var.nc outfile_${ii}${ij}${i}.nc
         done
        done
        done
        done
NUdu
  • 173
  • 6
  • 1
    Possible duplicate of [How to compare strings in Bash](https://stackoverflow.com/questions/2237080/how-to-compare-strings-in-bash) – Sean Pianka Nov 30 '18 at 20:20
  • What is `cdo`? It seems like it would be simpler to just iterate over the existing files and parse out the values to construct the new name. – chepner Nov 30 '18 at 20:21

1 Answers1

0

The smallest change is adding a continue for day 31 in month 9. You must test "09" as a string (or as 10#09).
(I also changed cdo ... into echo cdo ...)

for ii in 2007
do
   for i in 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #Day of the Month
   do
      for ij in 09 10 # Month
      do
         if [[ "${ij}" == "09" ]] && [[ "${i}" == "31" ]]; then continue; fi
         for j in 0000 0100 0200 0300 0400 0500 0600 0700 0800 0900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000 2100 2200 2300
         do
            echo "cdo cat DAS_0125_H.A${ii}${ij}${i}.${j}.002_var.nc outfile_${ii}${ij}${i}.nc"
         done
      done
   done
done

It would be easier to read when you use loop through the variales with a seq. You do not want to use `for ((i=1;i<=31;i++)) in view of the leading zeroes.
Also use verbose variable names.

for year in 2007
do
   for day in {01..31} # Day of the Month
   do
      for month in {09,10} # Month
      do
         if [[ "${month}" == "09" ]] && [[ "${day}" == "31" ]]; then continue; fi
         for hour in {00..23}
         do
            echo cdo cat DAS_0125_H.A${year}${month}${day}.${hour}00.002_var.nc outfile_${year}${month}${day}.nc
         done
      done
   done
done

When the files already exist, you can consider

ls DAS_0125_H.A2007{09,10}{01..31}.{00..23}00.002_var.nc |
   sed -r 's/.*([0-9]{8})/cdo cat & outfile_\1.nc/'

When this will show the commands you want, you can execute them by

source <(ls DAS_0125_H.A2007{09,10}{01..31}.{00..23}00.002_var.nc |
   sed -r 's/.*([0-9]{8})/cdo cat & outfile_\1.nc/')
Walter A
  • 19,067
  • 2
  • 23
  • 43