Languages and Scripting

String substitution is not working in shell script

 
Kauser
Advisor

String substitution is not working in shell script

Dear concern,

I've write following script.

bash-4.2$ cat truncate.sh
#!/bin/sh
LOGPATH="/wls_home/swig_atm/SwitchDbg"
ARCPATH="/wls_home/swig_atm/SwitchDbgArc"

for i in $LOGPATH/MSG*log
do
        if [ ! -e $i ]; then break ; fi
        #echo "For filename : $i"
        filename=`basename $i .log`
        dirname=`echo ${filename:4}`
        ofilename=`date +%H%M`
        #echo "target filename = $ARCPATH/$dirname/$dirname.$ofilename"
        if [ -e $ARCPATH/$dirname ];then
                mv $i "$ARCPATH/$dirname/$dirname.$ofilename"
        else
                mkdir -p $ARCPATH/$dirname
                mv $i "$ARCPATH/$dirname/$dirname.$ofilename"
        fi
done

 

But String substitution is not working in below arrow mentioned secton.  Please assist me,

bash-4.2$ sh -x truncate.sh
+ LOGPATH=/wls_home/swig_atm/SwitchDbg
+ ARCPATH=/wls_home/swig_atm/SwitchDbgArc
+ [ ! -e /wls_home/swig_atm/SwitchDbg/MSG_23March2021.log ]
+ + basename /wls_home/swig_atm/SwitchDbg/MSG_23March2021.log .log
filename=MSG_23March2021
+ truncate.sh[10]: ${filename:4}: The specified substitution is not valid for this command.===========>String substitution is not working
dirname=
+ + date +%H%M
ofilename=1743
+ [ -e /wls_home/swig_atm/SwitchDbgArc/ ]
+ mv /wls_home/swig_atm/SwitchDbg/MSG_23March2021.log /wls_home/swig_atm/SwitchDbgArc//.1743

 

1 REPLY 1
Steven Schweda
Honored Contributor

Re: String substitution is not working in shell script

> [...] String substitution is not working [...]

> bash-4.2$ [...]

   You may be using "bash" interactively, but your script uses a
different shell (with different features):

> #!/bin/sh

   That kind of parameter substitution is not a feature of that shell.

      man sh-posix      # Look for "Parameter Substitution".

There are alternatives . For example:

rux$ echo ${filename}
MSG_23March2021

rux$ echo ${filename#????}
23March2021

   Or, perhaps more generally:

rux$ echo ${filename#*_}
23March2021

   As usual, many things are possible.  (But not everything works with
every shell.)


   Also, in:
        dirname=`echo ${filename:4}`
what does
      `echo `
buy you?  Why not?:

        dirname=${filename#????}

 

   Alternatively, you could change your script to use "bash" (wherever
it is) instead of "/bin/sh", but I'd stick with "/bin/sh" for
portability/reliability.