bash script useful tips

I’ve spent last 2 days scripting virtual server deployment on Amazon cloud. For my reference, these are some useful commands I had to use to get the job done.
1. Hash “Hello World” string using SHA256 algorithm

echo -n "Hello World" | shasum -a 256

You can also hash a file

shasum -a 256 myfile.ext

2. Display server IP address by stripping out all other network information, including the local IP

ifconfig  | grep 'inet addr:'| grep -v '' | cut -d: -f2 | awk '{ print $1}'

3. Read out first 64 characters from a long string


4. While loop with 10 iterations

while [ $i -lt 10 ]
    echo $i

5. Replace contents of a file. For example search for string1, replace with string2 in myfile.txt

sed -e "s/string1/string2/g" myfile.txt > myfile.txt_temp
mv myfile.txt_temp myfile.txt

6. Display number of CPU processors on Linux
The command simply pulls out all instances of the word ‘processor’ from /proc/cpuinfo and returns the word count of it.

cat /proc/cpuinfo | grep processor | wc -l