Search code examples
shellunixsolaris

String expresion in Solaris not working


Does somebody know why the next code doesn't works in Solaris with KShell?

DATE=20180420
MONTH=`expr ${DATE:4:2}`
echo MONTH=$MONTH

It returns:

${DATE:4:2}: wrong substitution

Solution

  • Shell scripting syntax are different in different shell and hence you are getting this issue. If you run it in bash sell it will work for you in Solaris. So better change your script like below:-

     DATE=20180420
     MONTH=$(echo $DATE | cut -c 5-6) 
     echo MONTH=$MONTH
    

    The good thing is that it will work in all the shell in unix. Some more option here:-

    For day:-

    day=$(date +%d)
    

    For year in yy format:-

    year=$(date +%y)
    

    For year in yyyy format:-

    year=$(date +%Y)
    

    You can put the below line at the top of your script which will fix your issue.

     #!/bin/bash
     DATE=20180420
     MONTH=`expr ${DATE:4:2}` 
     # or MONTH=$(expr ${DATE:4:2}) 
     echo MONTH=$MON
    

    Hope this will help you.