Working with let command

Hi,

I need to find out the day of the year and it always needs to be 3 digits:

#!/bin/ksh
doy=`date '+%j'`
let doy=$doy-1
echo doy

Output is 36 , but I need it to print as 036

Appreciate any help on this.

I believe that the output of that script would always be:

doy

and never:

36

If you change:

echo doy

to:

printf '%03d\n' $doy

you should get something closer to what you want.

1 Like

Thanks a lot!!
Actually, I need to derive a filename from it.

${FILE_NAME_WO_EXTN}_${year}${doy}.ZIP . Can you please help me how can I use it here

Maybe something more like:

#!/bin/ksh
FILE_NAME_WO_EXTN="whatever"
YrDoy=`date '+%Y%j'`
filename="${FILE_NAME_WO_EXTN}_$((YrDoy - 1)).ZIP"
printf 'filename has been set to "%s"\n' "$filename"

Note, however, that this (and your earlier code) will probably not do what you want on January 1st each year.

Note also, that if you were calling date twice to assign values to year and doy (or any other two time/date values), that is dangerous. If the script is run close to midnight, there is always a chance that two or more invocations of date will be run on different days (or months, or even years). Without knowing how this string will be used and when your script will be invoked, it is hard to guess at whether or not this will be a problem in your environment.

But, getting the year and Julian day together does get rid of your problem with leading zeros being stripped by the decrement. If you don't want to use printf and you're dealing with non-negative integral values, you could also use typeset to specify that expansions of a given variable are to be right justified with zero fill to a given number of digits. For example, with ksh , the sequence of commands:

x=32
typeset -RZ3 x
echo "$x"

produces the output:

032
1 Like

Thanks!!
YrDoy=`date '+%Y%j'` works perfectly for me!!

Should your date command offer the -d option to supply a target date, this might come in handy and also handle the 1. January problem:

echo ${FILE_NAME_WO_EXTN}_$(date '+%Y%j' -d yesterday).ZIP
file_name_wo_extn_2017036.ZIP
1 Like

If the ksh being used is a recent version (such as 93u+ 2012-08-01 ), you could also use:

filename="$(printf '%s_%(+%Y%j)T.ZIP' "$FILE_NAME_WO_EXTN" yesterday)"
1 Like

The ksh typeset command has a -Z option such that

$ typeset -Z3 aa
$ aa=1
$ echo $aa
001

Andrew