- expr is useful for pattern matching and for counting number of
characters in string. For example:
expr $string : 'xxx\(.*\)' ## picks out stuff matched within ()
expr $string : '.*' ## length of string
It can also be used for arithmetic
VAR=`expr $VAR + 1` # increments VAR
although ksh's $(( )) is more convenient:
VAR=$(( VAR + 1 ))
- To get rid of blanks padding a string use:
STRING=$( echo $STRING )
- Instead of using LOGNAME to get a user name try following:
USER=$( id | sed -e 's/.*(//' -e 's/).*//' )
ID=$( id | sed -e 's/uid=//' -e 's/(.*//' )
- To handle terminals, use tput. For example, to output a word in bold:
BOLD=`tput smso`
BOLDOFF=`tput rmso`
echo "This is ${BOLD}portable${BOLDOFF}."
- While it is not possible for a child to change a parent's environment,
it is possible to make changes if both processes cooperate. For example,
if the child is an awk, the child can generate suitable
variable assignments and the parent can evaluate these:
eval "`awk -f program`" ## where awk program produces output like...
## VAR1=something
## VAR2=something_else
- Note that in variable assignments such as
${PAGER:=more}
the colon :
signifies that the empty string is to be treated the
same as an unset string (in this case the default more
is assigned in either case).
- Scripts should start
#!/usr/bin/*sh
not
#!/bin/*sh
- It not usually a good idea to give full path names for commands in a
shell, except perhaps for ls and rm which users may
have altered in undesirable ways. If you rely on the PATH variable
instead the script is more likely to be portable.
- Useful filters:
xargs - for breaking long argument lists.
cut - useful in some situations instead of sed.