Pat Pat - 1 year ago 81
Bash Question

unix shell script to get nth business day

Referencing the solution posted on this thread for getting the Nth business day of the month, I tried to get the 16th business day of the month using the following code, but it doesn't work.

BUSINESS_DAYS=`echo $($currCal|nawk 'NR>2 {print substr($0,4,14)}' |tr "\n" " ")`

The error when executing this is:

nawk: syntax error at source line 1 context is
NR>2 {print >>> substr(test. <<< sh,4,14)}
nawk: illegal statement at source line 1

I'm guessing it takes
as the script name, causing the syntax error. Please help.

Answer Source

There seem to be a few issues with what you have above.

First, I agree with @John1024 that in order to get the nawk error you've posted, you must actually be running:

BUSINESS_DAYS=`echo $($currCal|nawk "NR>2 {print substr($0,4,14)}" |tr "\n" " ")`

with double quotes around the nawk script.

Furthermore, once you resolve the nawk error, you're going to run into issues with how you are using currCal. You get the actual output of the cal command into the currCal variable, but then are using the variable value (that is the output of cal) as a command before the | rather than echoing it into the pipe or something similar.

This brings up an additional question of why you're using echo on the result of a subshell command (the $() part) within another subshell (the outer ``s).

Finally, the two lines you show above only get a list of the business days in the current month into the BUSINESS_DAYS variable. They do not output/save the 16th such day.

Taking all of the above into consideration (and also changing to use the $() subshell syntax consistently), you might want one of the following invocations:

If you really need to cache the current month's calendar and want to pull multiple days:

BUSINESS_DAYS="$(echo "${currCal}" | \
                    nawk 'NR>2 {print substr($0,4,14)}' | \
                    tr "\n" " ")"

DAYTH_DAY="$(echo "${BUSINESS_DAYS}" | nawk -v "day=${DAY}" '{ print $day }')

If this is just a one-and-done:

DAYTH_DAY="$(/usr/bin/cal | \
                nawk 'NR>2 {print substr($0,4,14)}' | \
                tr "\n" " " | \
                nawk -v "day=${DAY}" '{ print $day }')"

One more note: the processing here can be simplified if done entirely in awk(/nawk), but I wanted to stick to the basic framework you had already chosen.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download