Pages

Stupid bash codes

I was trying some simple linux codes , months ago. I was logged into my ubuntu and I found some of my old works. I thought, better post it on my blog as a reference than to keep it useless.

First example
 
#!/bin/bash
echo "This is my kind of first script on this computer"
echo "The number of arguments is $#"

Just a couple of hints
  • # in the beginning of the statement is used as a comment
  • $# is a expression which returns number of arguments

For Loop Example

#!/bin/bash
for planet in mercury venus earth mars jupiter saturn uranus neptune pluto
do
 echo  "$planet";
# echo "another planet"
done;

Now this one is a little advanced. Write below text in a file named file1.txt
123a45
my name is rajan
 The cat is actually a cat
And the actual bash script which is going to read the above file and give some output

#!/bin/bash

#getting the character count
a=`cat file1.txt | wc -c`

#delete the alphabets and count the remaining characters
#b=echo "$a" | tr -d [:alpha:] | wc -c
b=`cat file1.txt | tr -d [:alpha:] | wc -c`


if [[ $a -eq $b ]]
then
 echo " The file contains no alphabets"
else
 echo " The file contains alphabets"
fi


What the script does is, it counts the number of character in variable a. Then it deletes the alpha characters, count the remaining characters and assign the count to b. Now if originally there were no character, both a and b would be same in which case it would display "The file contains no alphabets" as you could see in the code.

The tr is a special text manipulation command. There are other powerful text manipulation commands like awk, sed etc.

Another simple example.
#!/bin/bash

#dont use space between variable_name and = and value
count=99
hundred=100


if [ $count -eq 100 ]
then
  echo "Count is 100"
else
  echo "Count is not 100"
fi

#use operator [[ rather than [
if [[ $count -lt $hundred ]]
then
 echo "count less than hundred"
else
 echo "count is greater than hundred"
fi

No comments:

Post a Comment

If you like to say anything (good/bad), Please do not hesitate...