Search code examples
solarisksh

Format string on Linux and Solaris


I have a Korn Shell script, and one part of it is that it takes a given date in YYYYMMDD format and outputs it in YYYY/MM/DD format. At first I tried

typeset displaystart=`date --date="${gbegdate}" '+%Y/%m/%d'`

which works fine on Linux, but Solaris's date doesn't have a --date option. I then tried

typeset displaystart=`echo ${gbegdate:0:4}`/`echo ${gbegdate:4:2}`/`echo ${gbegdate:6:2}`

which also works on Linux, but on Solaris it just outputs //.

How can I format this date string in a way that works on Linux and Solaris?


Solution

  • Korn shell doesn't have ${variable:start:length} syntax; this is a bash extension to POSIX shell syntax.

    You can use echo "$variable" | cut -cstart-end instead.

    typeset displaystart=`echo $gbegdate | cut -c1-4`/`echo $gbegdate | cut -c5-6`/`echo $gbegdate | cut -c7-8`
    

    Or maybe you could change your script to use bash instead of ksh.