Table of contents
For loop
Handling Spaces
for loop uses $IFS variable to determine what the field separators are. By default $IFS is set to the space character.
#!/bin/bash SAVEIFS=$IFS IFS=$(echo -en "\n\b") for f in * do echo "$f" done IFS=$SAVEIFS
Arithmetic
Summing the memory usage of processes
unset SUM for i in `ps -eAo rss,command|grep httpd|awk '{print $1}'`;do SUM=$((SUM+$i)) done echo $SUM"KB"
Incrementing software versions
for f in $(find . -name gradle.properties); do NEW_VER=`perl -pe 's/(version=[0-9]+\.[0-9]+\.)([0-9]+)/$1.($2+1)/e' $f | egrep "^version="` sed -i '' "s/version=[0-9]\{1,\}\.[0-9]\{1,\}\.[0-9]\{1,\}/${NEW_VER}/g" $f done
fixing email timestamps
for i in `ls -C1`; do DATE=$(grep Delivery-date $i |cut -c 16-40); touch --date="$DATE" $i;done
tr (trim/translate)
converting case
echo something | tr [:lower:] [:upper:]
deleting digits
echo something | tr -d [:digit:]
Arrays
Array elements may be initialized with the variablexx notation. Alternatively, a script may introduce the entire array by an explicit declare ?avariable statement. To dereference (find the contents of) an array element, use curly bracket notation, that is, ${variablexx}
adding a value into an array
Append to new element
variable=( "${variable[@]}" "new value" )
update specific element
variable=( "${variable[3]}" "new value" )
printing values from an array
Print all elements
$ echo ${variable[@]}
Number of elements in array
$ echo ${#variable[*]}
basic adding in new elements example
for OUTPUT in $(some command that returns multi-line output);do MY_OUTPUT_ARRAY=( "${MY_OUTPUT_ARRAY[@]}" "$(echo "${OUTPUT}\n")" ) done # print out every record of the array one after the other echo -e "${MY_OUTPUT_ARRAY[@]}"