Translating #!/bin/ksh date conversion function into #!/bin/sh
I used this ksh function for converting "1-Jan-2011" format to "1.1.2011."
#!/bin/ksh
##---- function to convert 3 char month into numeric value ----------
convertDate()
{
echo $1 | awk -F"-" '{print $1,$2,$3}' | read day mm yyyy ## split the date arg
typeset -u mmm=`echo $mm` ## set month to uppercase
typeset -u months=`cal $yyyy | grep "[A-Z][a-z][a-z]"` ## uppercase list of all months
i=1 ## starting month
for mon in $months; do ## loop thru month list
## if months match, set numeric month (add zero if needed); else increment month counter
[[ "$mon" = "$mmm" ]] && typeset -xZ2 monthNum=$i || (( i += 1 ))
done ## end loop
echo $day.$monthNum.`echo $yyyy | cut -c3-` ## return all numeric date format ddmmyyyy
}
But I need to use this function with #!/bin/sh. So I tried rewriting it...
#!/bin/sh
##---- function to convert 3 char month into numeric value ----------
convertDate()
{
echo $1 | awk -F"-" '{print $1,$2,$3}' | read day mm yyyy ## split the date arg
echo $mm #IT SEEMS LIKE THE PROBLEM IS IN THE 开发者_StackOverflow中文版PREVIOUS LINE, BECAUSE THIS VARIABLE IS EMPTY IN #!/bin/sh, BUT IF YOU CHANGE IT TO #!/bin/ksh EVERYTHING SEEM TO BE FINE, THEN FUNCTION WORKS CORRECTLY.
mmm=`echo $mm | tr '[a-z]' '[A-Z]'`
months=`cal $yyyy | grep "[A-Z][a-z][a-z]" | tr '[a-z]' '[A-Z]'`
i=1 ## starting month
for mon in $months; do ## loop thru month list
## if months match, set numeric month (add zero if needed); else increment month counter
if [ "$mon" = "$mmm" ]; then
monthNum=`printf '%02d' $i`
else
i=`expr $i + 1`
fi
done ## end loop
echo $day.$monthNum.`echo $yyyy | cut -c3-` ## return all numeric date format ddmmyyyy
}
convertDate "20-May-2010"
But it doesn't work (read the UPPERCASE comment in the last script) :(
Help!
The problem is that whether the read
command runs in a subshell due to the pipeline depends on exactly which shell /bin/sh
is; you will get one behavior from bash
and another from legacy UNIX (e.g. Solaris) /bin/sh
. Use set
instead.
set -- `echo $1 | awk -F"-" '{print $1,$2,$3}'`
although I would probably write
oIFS="$IFS"
IFS=-
set -- $1
IFS="$oIFS"
精彩评论