Bash Basics
From #LinuxWiki
Contents |
[edit] Mathematics
Bash includes full mathematical functionality (theres no need to use expr at all). Just be sure to include all your math work inside double brackets.
N=0 ; TOTAL=0 while ((N<100)) do ((TOTAL=TOTAL+N)) ((N=N+1)) done echo "Total is $TOTAL" echo "Average is $((TOTAL/(N-1)))"
Total is 4950 Average is 50
[edit] Strings
[edit] Search/Replace
[edit] Single Occurrance
A="Windows Rules"
echo ${A/Windows/Linux}
Linux Rules
[edit] Multiple Occurances
A="The cob sob on the mob"
echo ${A//ob/at}
The cat sob on the mob
[edit] Trimming
Bash allows you to remove from the left and right of strings using the ${#} and ${%} functions.
[edit] Right Trim
# Rename all files ending in .doc to end in .odf
for FN in *.doc
do
mv $FN ${FN%.doc}.odf
done
${%} matches against the shortest match when a wildcard is specified - for example -
A="Get Rid of the Xs XXXXXXXXXXXXXXXX"
echo ${A%X*}
Get Rid of the Xs XXXXXXXXXXXXXXX
Whereas ${%%} removes the largest match -
A="Get Rid of the Xs XXXXXXXXXXXXXXXX"
echo ${A%%X*}
Get Rid of the
[edit] Left Trim
${#} works similarly to ${%} only working on the left side of a string.
MOBILE="+447123456789"
NEWMOBILE="0${MOBILE#+44}"
echo "$MOBILE is now $NEWMOBILE"
+447123456789 is now 07123456789
[edit] Useful Examples
RUNME=/usr/local/bin/runme
PATH=${RUNME%/*}
BASENAME=${RUNME##*/}
echo "PATH is $PATH, Basename is $BASENAME"
PATH is /usr/local/bin, Basename is runme

