Translating #!/bin/ksh date conversion function into #!/bin/sh

孤者浪人 提交于 2019-12-14 03:19:41

问题


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 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!


回答1:


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"


来源:https://stackoverflow.com/questions/6245246/translating-bin-ksh-date-conversion-function-into-bin-sh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!