vendredi 8 août 2014

KSH eval / variable subtitution / variable test

from :http://b62.tripod.com/doc/docksh.htm

OTHER FUNCTIONALITIES


cmd1 || cmd2    exec cmd2 if cmd1 fail
cmd1 && cmd2    exec cmd2 if cmd1 is OK

V1=${V2:=V3}    Set V1 with the value of V2 if this is set else set the
                variable V1 with value of V3 (V3 could be a number).
                sh replacement:  if [ $V2 ] ; then
                                                V1=$V2
                                 else
                                                V1=$V3
                Example: DisplaySize=${LINES:24} ; Command=${Command:"cat"}


${V1:?word}     if V1 set  & V1!=null   ret $V1 else print word and exit
                  : ${V1:?"variable V1 not set on null"}
${V1:=word}     if V1 !set | V1==null   set V1=$word
${V1:-word}     if V1 set  & V1!=null   ret $V1 else ret word
${V1:+word}     if V1 set  & V1!=null   ret word else ret nothing
${V1##patt}
${V1#patt}      if patt are found at the begin of V1 return V1 whitout the patt
                else return V1
                V1="lspwd" ; ${V1#"ls"}  # exec pwd
${V1%%patt}
${V1%patt}      if patt are found at the end of V1 return V1 whitout the patt
                else return V1
                V1="lspwd" ; ${V1%"pwd"}  # exec ls 
 
 
from : http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html 
Variable Manipulations

Removing something from a variable

Variables that contain a path can very easily be stripped of it: ${name##*/} gives you just the filename.
Or if one wants the path: ${name%/*}. % takes it away from the left and # from the right.
%% and ## take the longest possibility while % and # just take the shortest one.

Replacing a variable if it does not yet exits

If we wanted $foo or if not set 4 then: ${foo:-4} but it still remains unset. To change that we use:
${foo:=4}

Exiting and stating something if variable is not set

This is very important if our program relays on a certain vaiable: ${foo:?"foo not set!"}

Just check for the variable

${foo:+1} gives one if $foo is set, otherwise nothing.
 

Aucun commentaire:

Enregistrer un commentaire