Showing posts with label Scripts. Show all posts
Showing posts with label Scripts. Show all posts

Friday, August 5, 2011

Limited Shell


we want to limit the activities or command to run for specific user then, how to limit a shell? here are the steps to create limited shell.
Add a user who can execute some specific commands.
1. Create a link named ‘rbash’ from bash.
[root@divyajyot ~]# ln -s /bin/bash /opt/rbash
2. Add a user that his default shell is rbash and set he can execute only ‘ping’.
[root@divyajyot ~]# useradd lsuser -s /opt/rbash
[root@divyajyot ~]# passwd lsuser
[root@divyajyot ~]# mkdir /home/lsuser/bin
[root@divyajyot ~]# ln -s /bin/ping /home/lsuser/bin/ping
[root@divyajyot ~]# chown root. /home/lsuser/.bash_profile
[root@divyajyot ~]# chmod 755 /home/lsuser/.bash_profile
[root@divyajyot ~]# vi /home/lsuser/.bash_profile
  # change PATH like follows
  PATH= $HOME/bin
3. Login with the test user.
[lsuser@divyajyot ~]$ cd
-rbash: cd: restricted # denied
[lsuser@divyajyot ~]$ ls
-rbash: ls: command not found # none
[lsuser@divyajyot ~]$ ping localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.045 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.008 ms
64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.008 ms
— localhost ping statistics —
3 packets transmitted, 3 received, 0% packet loss, time 2157ms
rtt min/avg/max/mdev = 0.008/0.020/0.045/0.017 ms  # executed

Saturday, July 23, 2011

Change the Terminal Background Color

"tput" is a standard Unix operating system command which is used to
set terminal features. Depending on the system, tput uses the terminfo
or termcap database, as well as looking into the environment for the
terminal type.


Change the Terminal Background Color using tput setb

Using tput, the background color of the screen can be changed as shown below.

$ tput setb 4

Change the Foreground Color using tput setf

You can also change the foreground color of the terminal as shown below.

$ tput setf 5

Note: If you set foreground and background to the same color you
cannot see the cursor. So, to reset, execute “tput reset”.

Color info:  1: red, 2: Green, 3= Yellow, 4= Blue, 5= Purple, 6= Cyan, 7= White

Thursday, April 7, 2011

BIRTH OF THE FAMOUS NAMES....!!!



GOOGLE 
The name started as a joke boasting about the amount of information the search-engine would be able to search. It was originally named 'Googol', a word for the number represented by 1 followed by 100 zeros. After founders- Stanford graduate students Sergey Brin and Larry Page presented their project to an angel investor, they received a cheque made out to 'Google' ...thus the name.


HOTMAIL
Founder Jack Smith got the idea of accessing e-mail via the web from a computer anywhere in the world. When Sabeer Bhatia came up with the business plan for the mail service, he tried all kinds of names ending in 'mail' and finally settled for hotmail as it included the letters "html" - the programming language used to write web pages. It was initially referred to as HoTMaiL with selective uppercasing. 


Bill Hewlett and Dave Packard tossed a coin to decide whether the company they founded would be called Hewlett-Packard or Packard-Hewlett.


INTEL

Bob Noyce and Gordon Moore wanted to name their new company ' Moore Noyce'but that was already trademarked by a hotel chain so they had to settle for an acronym of INTegrated ELectronics.


LOTUE (Notes)



Mitch Kapor got the name for his company from 'The Lotus Position' or 'Padmasana'. Kapoor used to be a teacher of Transcendental Meditation of Maharishi Mahesh Yogi. 


Coined by Bill Gates to represent the company that was devoted to MICROcomputer SOFTware. Originally christened Micro-Soft, the '-' was removed later on.

MOTOROLA

Founder Paul Galvin came up with this name when his company started manufacturing radios for cars. The popular radio company at the time was called Victrola. 


ORACLE

Larry Ellison and Bob Oats were working on a consulting project for the CIA (Central Intelligence Agency). The code name for the project was called
Oracle (the CIA saw this as the system to give answers to all questions or something such). The project was designed to help use the newly written SQL code by IBM. The project eventually was terminated but Larry and Bob decided to finish what they started and bring it to the world. They kept the name Oracle and created the RDBMS engine. Later they kept the same name for the company
.


SONY
It originated from the Latin word 'sonus' meaning sound, and 'sonny' a slang used by Americans to refer to a bright youngster.
SUN 
Founded by four Stanford University buddies, SUN is the acronym for Stanford University Network. Andreas Bechtolsheim built a microcomputer; Vinod Khosla recruited him and Scott McNealy to manufacture computers based on it, and Bill Joy to develop a UNIX-based OS for the computer.

YAHOO! 
The word was invented by Jonathan Swift and used in his book 'Gulliver's Travels'. It represents a person who is repulsive in appearance and action and is barely human. Yahoo! Founders Jerry Yang and David Filo selected the name because they considered themselves yahoos. 

Tuesday, February 22, 2011

How to use find with boolean operators AND, OR, NOT


In these days when disk are everyday bigger and bigger as well as cheaper, you will find yourself storing everything, we almost never delete a file anymore, we just store it. But, I do not know about yourself, but sometimes it happens to me, that I can’t just remember where a given file, picture, or song was archived.
So, I know I have it, somewhere in my disk, but not know where. You you might think I am not too organized, and you will be right with that statement, :).
What I do, is to use find to locate those missed files, find is extremely powerful, and I’ve written about it in the past, for example:
Today, I just want to give you a small tip about it, and it is how to combine searches using boolean operators like:
  • AND
  • OR
  • NOT

Find and boolean operators

Let’s do this by examples, and to start let’s suppose I want to find the files with .png and .jpg extensions.
find /path/ -name '*.png' -or -name '*.jpg'
This way, files with .jpg or .png in other words image files.
Now, let’s imagine we need to find movies that are bigger than a certain size.
find /path/ -name '*.mpeg' -and -size +300000k
So, we will find only files ending in .mpeg and bigger than 300 Mega bytes of size.
I’m sure you will find other applications.

Tuesday, February 1, 2011

export environment variable from a bash script


You may want to create a bash script that export some environment variable for your shell, but infect every execution of bash script is a unique session, where the variable export within it can’t be carry backward back to the bash shell.
For example you have a env.sh which contains some environment variables
export HELLO=hello
export HELLO2=world
And you trying to execute the env.sh, then try to echo $HELLO $HELLO2 at your shell, you will get nothing.
The proper way to export environment variable from your script to your shell is using command source.
source env.sh
echo $HELLO $HELLO2
$ hello world
You can put your env.sh into /usr/bin, and you can do source env.sh at any location and it will still works. Just that you have to educate your users to use source instead of direct execute the script. But I realized that not much users aware of the source command.
There is always an alternative way to do the same thing in Linux world. You can create a new bash session from your bash script and make it stay there until user type ‘exit’. Bash support an interactive option for that.
bash -i
Ok, how to make use of it?
Let me gives you a case and explain why I wanna make use of bash -i instead of source.
As an embedded Linux programmer, sometimes I may need to compile some apps by using different set of toolchain based on the embedded device ’s processor architecture. The common environment variable for toolchain are ARCH and CROSS_COMPILE. Besides that, I also want to remind the user regarding that particular shell is meant for building apps for embedded device, therefore I would like to change the color and format of existing bash prompt, which i can make use of PS1 variable.
build_arm.sh
#!/bin/bash
export ARCH=arm
export CROSS_COMPILE=arm-none-linux-gnueabi-
export PS1="\e[31mBUILD_ARM \w \e[m\n\$"

bash -i
When execute build_arm.sh, the bash prompt will turn red, and environment variable for ARCH and CROSS_COMPILE will be set, until user type ‘exit’, everything will resume back to normal. Why? because bash -i interactively wait for user inputs.
./build_arm.sh
BUILD_ARM ~
$

Monday, January 31, 2011

How to use GREP command in Shell


Introduction

Sometimes you remember a phrase or a given word or words, you put in a document, but you do not remember the name of the document. How to find it?, well do a search of all your documents, looking for that word or words or sentence, in other words, look for a string or strings.
Now, thanks to computers this is easier now, than it was in our parents' days.
If you are using Linux, you have grep to help on this job.

Look for a document, containing a given string

First the easy case, you know the exact sentence, you are looking for, and you at least remember the folder where the file is.
grep "sentence to look for" /home/user/docs/
Now, let's suppose you do not know if the sentence was in uppercase or in lowercase, so ask grep to ignore case.
grep -i "sentence to look for" /home/user/docs/
Well, let's suppose you have a lot of sub-folders, and you do not remember where your file is.
grep -r "sentence to look for" /home/user/docs/
Let's see an example of the output in my PC
grep -ri "Introduction" /home/user/post/
The output is:
/home/user/post/monthy-newsletter.txt:###Introduction###
/home/user/post/monthy-newsletter.txt:I'm no expert in MySQL, but anyway I have written three introduction-type MySQL posts, something we all need to know to start [how to create databases][1], [How to list those databases][2] and [How to create tables in MySQL][3]
/home/user/post/how-to-debug-bash-shell-scripts.txt:##Introduction##
/home/user/post/how-to-setup-dns-bind-master-slave-linux.txt:##Introduction
/home/user/post/interview-raphael-hertzog.txt:I also have plans for bigger changes concerning Debian, and among them is the introduction of Debian Rolling, a distribution similar to testing but with some design choices to make it more usable at any point in time.
/home/user/post/four-years-with-debian-testing.txt:##Introduction##
Binary file /home/user/post/.find-a-documents-with-given-string.txt.swp matches
/home/user/post/how-to-change-the-priority-of-Linux-processes.txt:##Introduction##
As you can see there are some binary files, also scanned, if we want to avoid that:
grep -riI "introduction" /home/user/post/
The output now is:
/home/user/post/monthy-newsletter.txt:###Introduction###
/home/user/post/monthy-newsletter.txt:I'm no expert in MySQL, but anyway I have written three introduction-type MySQL posts, something we all need to know to start [how to create databases][1], [How to list those databases][2] and [How to create tables in MySQL][3]
/home/user/post/how-to-debug-bash-shell-scripts.txt:##Introduction##
/home/user/post/how-to-setup-dns-bind-master-slave-linux.txt:##Introduction
/home/user/post/interview-raphael-hertzog.txt:I also have plans for bigger changes concerning Debian, and among them is the introduction of Debian Rolling, a distribution similar to testing but with some design choices to make it more usable at any point in time.
/home/user/post/four-years-with-debian-testing.txt:##Introduction##
/home/user/post/how-to-change-the-priority-of-Linux-processes.txt:##Introduction##
Finally, I just want the file names, and not the sentences where the sentence or word appears.
grep -riIl "introduction" /home/user/post/
The output will be:
/home/user/post/monthy-newsletter.txt
/home/user/post/how-to-debug-bash-shell-scripts.txt
/home/user/post/how-to-setup-dns-bind-master-slave-linux.txt
/home/user/post/interview-raphael-hertzog.txt
/home/user/post/four-years-with-debian-testing.txt
/home/user/post/how-to-change-the-priority-of-Linux-processes.txt

Conclusion

I know, you may use other ways, maybe find, but I like this method, and use it a lot, just like the advanced search function in Gmail :

Sunday, January 9, 2011

String and pipe command together in Linux shell

Introduction

When you are working in the Linux command line, you often need to type several commands in a succession, you can type one, wait until it finishes and then type the next one, or you can type all of them in a line, and they will execute in order.
There are various ways to execute commands in a line, I mean one after the other, we’ll see some of them in this article, so you can pick the best for your needs depending on the situation.

String commands in Linux using semi colon

This is the simplest way, for example:
 
htop ; free ; df -h

What you will get is htop executed, once you leave it, free will execute and output its info to the screen, immediately you will see the output of df -h on your screen.
It does not matter if the command is successful or not. So if you made a mistake and type this:
 
fre ; df -h

The output will be something like this:
 
bash: fre: command not found
Filesystem            Size  Used Avail Use% Mounted on
udev                   10M  212K  9.8M   3% /dev
/dev/disk/by-uuid/fc8f5296-7bd8-463a-87af-87c6d2215ff9
                       41G   23G   16G  59% /
none                 1004M  102M  903M  11% /dev/shm

You get the command not found error and then df -h is executed, so if you need that the first command be successful to execute the second or third one, do not use this method.

String commands in Linux using double ampersand (&&)

This is maybe one of the most known ways to string commands together in Linux, it works more or less the same as with the semi-colon, but it will check for errors in each command on the line before going to the next one.
This is great if you are compiling software to install it. For example:
 
./configure && make && make install

This way if any of the commands configure or make gives any error, the next one in the line will not be executed and all the execution is stopped.

String commands in Linux using double pipe (||)

With the double pipe “||” you are telling the shell that it should only execute the next command if the first one has errors. You can use it, if you want to perform an action and there are two ways to do it, so, you can join both of them with double pipes, and if the first one fails the second one will be executed.
Just as an example.
 
vmstat || free

So, only in the event you do not have vmstat installed (do not really know if that is possible) free will be executed, and you will have one way or the other the memory info your Linux box.
I’m sure you will find better applications :).

Pipe commands together with pipe (|)

Using a single pipe “|” to string Linux commands together will make another interesting thing, it will forward the output of one command to the other, the next command in the line, will use that output as its input.
I use this a lot when writing post for my blog, I write my post using vim and with markdown syntax, then I use the perl program to translate it to html, but also use smartypants, so I use a line like this:
 
/html-tools/markdown.pl mypost.txt | /html-tools/smartypants.pl | xclip -selection clipboard

That way, markdown.pl translate mypost.txt to html, then smartypants.pl adds the typographic punctuation HTML entities, and finally its output goes to my clipboard using xclip which I can just paste in my drupal blog.

Final notes

As you can see pipe commands in Linux is easy, and you have one option for each need, hope you find the one for your needs here.
If you have more examples or better ways to achieve these task, please share in the comments.
  

Stop or suspend a running process in Linux

Introduction

If you start a process on a terminal, being it local or a remote (ssh) terminal, you normally loose the control of the terminal while the process is running, then if you want to recover that control, you have some options.

Cancel the process

By pressing CTRL+C you can stop a running process, and recover the control of your terminal, this will tell to the running application to stop anything it is doing at that moment and shut down.

Suspend a process

Another way, is to suspend the process for a moment, you will use CTRL+Z for this, then you can resume the job in any moment, when you feel like to.

Restore your stopped processes

You have now two different ways to re-start your stopped processes, you can send them to the foreground or to the background, to send it to foreground execute:
 
fg n

To send them to background execute:
 
bg n

Where n is the number of the stopped process, and you will see it in brackets when stop it.
Like this:
 
[admin@arch ~]$ amsn                                                                                                                         
^Z                                                                                                                                             
[1]+  Stopped                 amsn

You can see that the stopped process is amsn and its identifying number is “1”. Now, if you ever forget the number, you can run:
jobs
you will get an output like this one:
 
[admin@arch ~]$ jobs
[1]+  Stopped                 amsn

How to change the priority of a Linux process

Introduction

The Linux Kernel will take care of the time each process, will have to use the processor, but you can change that, by changing the priority.
When is this needed?, well usually never, but if you have a not to fast PC, and you are compiling something, and at the same time having a video conferencing, you may want to increase the priority of your video conference applications, while reducing the priority of the program compiling your software.

How to increase or decrease priority

We will use nice in order to change the priority of a given process, first you need to know the PID of the program you want to re-prioritize. You can use pstree or htop to discover the PID, if you use pstree use it with the -p option.
 
pstree -p

Once you know the PID of the process you want to change its priority, use renice to change it.
The permitted range is from “-20” to “20” being “-20” the highest priority.
As root run:
 
renice -8 -p 123

To assign a priority of -8 to a process with a PID of 123
Remember that only root can increase the priority, and normal users, can only alter the priority owned by them, and only to decrease its priority, and not to increase it.
Read the man page of renice: also keep in mind that you may need to change the priority of a parent process to affect all children processes. As an example, I usually have 5 to 6 firefox processes, all nested to a parent process, so, work with the parent. Use pstree to find the parent.

Tuesday, December 21, 2010

Linux Changing Run Levels


Recently I was taking class for Linux sys admin course. Some one asked me "How do changing run levels affect us or our users?" I replied with following answer:
Well if you are moving to higher run levels, you may make additional services available to users, while moving to a lower run level will causes to services (daemons) to become unavailable. On production server run level 3 is the normally used and rarely changed. However some administrative tasks require the administrator to move system to run level 1 i.e single user mode.
Use the init command to change rune levels:
# init 1
Runlevel and usage:
  • Runlevel 0 is halt
  • Runlevel 1 is single-user
  • Runlevels 2-5 are multi-user (some distro uses RUN level 5 to start X [KDE/Gnome])
  • Runlevel 6 is for rebooting system
Typing init 3 will move system to run level 3:
# init 3
On most Linux server system default run level is 3 and on most Linux Desktop system default run level is 5. The default run level is defined by the initdefault line at the top of /etc/inittab. So if you wanna change default run level open file /etc/inittab and edit entry initdefault:
# vi /etc/inittab
Set initdefault to 5, so that you can boot to X next time when Linux comes up:
id:5:initdefault:
Save file and reboot to see changes.
getty is the program which opens a tty port, prompts for a login name and password (via /bin/login command). Your console displays a login/password prompt at run levels 1 through 6. You can use ALT+F1...ALT+F6 keys to switch console (use CTRL+ALT+F1..F6 under X windows).
However my experience so far is that students get confused with ssh and KDE/Gnome Desktop login.
SSH logins are handled by sshd server which starts at run level 2/3. KDE/Genome Desktop login are handled by GDM/XDM/KDM display manager which starts at run level 5 (however Debian Linux and some other distro can start them from run level 2 via special rc.d script located in /etc/init.d/gdm)

Saturday, December 4, 2010

Shell Script Examples (Problem & Solution)

ARRAY in Shell Script


#!/bin/bash
#Declare array with 4 elements
ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}

# echo each element in array
# for loop
for (( i=0;i<$ELEMENTS;i++)); do
    echo ${ARRAY[${i}]}
done

Shell Script Examples (Problem & Solution)

Perform Arithmetic Operation 



#!/bin/bash

echo '### let ###'
# bash addition
let ADDITION=3+5
echo "3 + 5 =" $ADDITION

# bash subtraction
let SUBTRACTION=7-8
echo "7 - 8 =" $SUBTRACTION

# bash multiplication
let MULTIPLICATION=5*8
echo "5 * 8 =" $MULTIPLICATION

# bash division
let DIVISION=4/2
echo "4 / 2 =" $DIVISION

# bash modulus
let MODULUS=9%4
echo "9 % 4 =" $MODULUS

# bash power of two
let POWEROFTWO=2**2
echo "2 ^ 2 =" $POWEROFTWO


echo '### Bash Arithmetic Expansion ###'
# There are two formats for arithmetic expansion: $[ expression ]
# and $(( expression #)) its your choice which you use

echo 4 + 5 = $((4 + 5))
echo 7 - 7 = $[ 7 - 7 ]
echo 4 x 6 = $((3 * 2))
echo 6 / 3 = $((6 / 3))
echo 8 % 7 = $((8 % 7))
echo 2 ^ 8 = $[ 2 ** 8 ]


echo '### Declare ###'

echo -e "Please enter two numbers \c"
# read user input
read num1 num2
declare -i result
result=$num1+$num2
echo "Result is:$result "

# bash convert binary number 10001
result=2#10001
echo $result

# bash convert octal number 16
result=8#16
echo $result

# bash convert hex number 0xE6A
result=16#E6A
echo $result

Shell Script Examples (Problem & Solution)

Problem : How to write shell script that will add two nos, which are supplied as command line argument, and if this two nos are not given show error and its usage.

Solution :


if [ $# -ne 2 ]
then
echo "Usage - $0 x y"
echo " Where x and y are two nos for which I will print sum"
exit 1
fi
echo "Sum of $1 and $2 is `expr $1 + $2`"
Pro Bash Programming: Scripting the GNU/Linux Shell (Expert's Voice in Linux)
--------------------------------------------------------------------------------------------------------


Problem : Write Script to find out biggest number from given three nos. Nos are supplies as command line argument. Print error if sufficient arguments are not supplied.

Solution : 

#
# Algo:
# 1) START: Take three nos as n1,n2,n3.
# 2) Is n1 is greater than n2 and n3, if yes
# print n1 is bigest no goto step 5, otherwise goto next step
# 3) Is n2 is greater than n1 and n3, if yes
# print n2 is bigest no goto step 5, otherwise goto next step
# 4) Is n3 is greater than n1 and n2, if yes
# print n3 is bigest no goto step 5, otherwise goto next step
# 5) END
#
#

if [ $# -ne 3 ]
then
echo "$0: number1 number2 number3 are not given" >&2
exit 1
fi
n1=$1
n2=$2
n3=$3
if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]
then
echo "$n1 is Bigest number"
elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]
then
echo "$n2 is Bigest number"
elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]
then
echo "$n3 is Bigest number"
elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]
then
echo "All the three numbers are equal"
else
echo "I can not figure out which number is biger"
fi
Pro Bash Programming: Scripting the GNU/Linux Shell
------------------------------------------------------------------------------------------------------------
Problem : Write script to print nos as 5,4,3,2,1 using while loop.


Solution : 

# Algo:
# 1) START: set value of i to 5 (since we want to start from 5, if you
# want to start from other value put that value)
# 2) Start While Loop
# 3) Chechk, Is value of i is zero, If yes goto step 5 else
# continue with next step
# 4) print i, decement i by 1 (i.e. i=i-1 to goto zero) and
# goto step 3
# 5) END
#
i=5
while test $i != 0
do
echo "$i
"
i=`expr $i - 1`
done
Linux Command Line and Shell Scripting Bible
-------------------------------------------------------------------------------------------------------------
Problem : Write Script, using case statement to perform basic math operation as
follows
+ addition
- subtraction
x multiplication
/ division
The name of script must be 'q4' which works as follows
$ ./q4 20 / 3, Also check for sufficient command line arguments

Solution : 

if test $# = 3
then
case $2 in
+) let z=$1+$3;;
-) let z=$1-$3;;
/) let z=$1/$3;;
x|X) let z=$1*$3;;
*) echo Warning - $2 invalied operator, only +,-,x,/ operator allowed
exit;;
esac
echo Answer is $z
else
echo "Usage - $0 value1 operator value2"
echo " Where, value1 and value2 are numeric values"
echo " operator can be +,-,/,x (For Multiplication)"
fi
Write Script to see current date, time, username, and current directory.
echo "Hello, $LOGNAME"
echo "Current date is `date`"
echo "User is `who i am`"
echo "Current direcotry `pwd`"
Linux Command Line and Shell Scripting Bible
-------------------------------------------------------------------------------------------------------------
Problem : Write script to print given number in reverse order, for eg. If no is 123 it must print as 321.


Solution : 


# Algo:
# 1) Input number n
# 2) Set rev=0, sd=0
# 3) Find single digit in sd as n % 10 it will give (left most digit)
# 4) Construct revrse no as rev * 10 + sd
# 5) Decrment n by 1
# 6) Is n is greater than zero, if yes goto step 3, otherwise next step
# 7) Print rev
#
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find reverse of given number"
echo " For eg. $0 123, I will print 321"
exit 1
fi

n=$1
rev=0
sd=0

while [ $n -gt 0 ]
do
sd=`expr $n % 10`
rev=`expr $rev \* 10 + $sd`
n=`expr $n / 10`
done
echo "Reverse number is $rev"
Classic Shell Scripting
-------------------------------------------------------------------------------------------------------------
Problem : Write script to print given numbers sum of all digit, For eg. If no is 123 it's sum of all digit will be 1+2+3 = 6.


Solution :


# Algo:
# 1) Input number n
# 2) Set sum=0, sd=0
# 3) Find single digit in sd as n % 10 it will give (left most digit)
# 4) Construct sum no as sum=sum+sd
# 5) Decrment n by 1
# 6) Is n is greater than zero, if yes goto step 3, otherwise next step
# 7) Print sum
#
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find sum of all digit for given number"
echo " For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"
exit 1
fi

n=$1
sum=0
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
sum=`expr $sum + $sd`
n=`expr $n / 10`
done
echo "Sum of digit for numner is $sum"
Mastering Unix Shell Scripting: Bash, Bourne, and Korn Shell Scripting for Programmers, System Administrators, and UNIX Gurus
-------------------------------------------------------------------------------------------------------------
Problem : How to perform real number calculation in shell script and store result to
third variable , lets say a=5.66, b=8.67, c=a+b?

Solution :


a=5.66
b=8.67
c=`echo $a + $b | bc`
echo "$a + $b = $c"
-------------------------------------------------------------------------------------------------------------
Problem : Write script to determine whether given file exist or not, file name is supplied as command line argument, also check for sufficient number of command line argument.


Solution : 


if [ $# -ne 1 ]
then
echo "Usage - $0 file-name"
exit 1
fi

if [ -f $1 ]
then
echo "$1 file exist"
else
echo "Sorry, $1 file does not exist"
fi
Learning the bash Shell: Unix Shell Programming (In a Nutshell (O'Reilly))
-------------------------------------------------------------------------------------------------------------
Problem : Write script to print contains of file from given line number to next given number of lines. For e.g. If we called this script as Q13 and run as
$ Q13 5 5 myf , Here print contains of 'myf' file from line number 5 to next 5 line of that file.


Solution : 

if [ $# -eq 0 ]
then
echo "$0:Error command arguments missing!"
echo "Usage: $0 start_line uptoline filename"
echo "Where start_line is line number from which you would like to print file"
echo "uptoline is line number upto which would like to print"
echo "For eg. $0 5 5 myfile"
echo "Here from myfile total 5 lines printed starting from line no. 5 to"
echo "line no 10."
exit 1
fi

#
# Look for sufficent arg's
#

if [ $# -eq 3 ]; then
if [ -e $3 ]; then
tail +$1 $3 | head -n$2
else
echo "$0: Error opening file $3"
exit 2
fi
else
echo "Missing arguments!"
fi
Linux Shell Scripting with Bash
-------------------------------------------------------------------------------------------------------------
Problem : Write script called sayHello, put this script into your startup file called .bash_profile, the script should run as soon as you logon to system, and it print any one of the following message in infobox using dialog utility, if installed in your system, If dialog utility is not installed then use echo statement to print message : -
Good Morning
Good Afternoon
Good Evening , according to system time.


Solution : 


temph=`date | cut -c12-13`
dat=`date +"%A %d in %B of %Y (%r)"`

if [ $temph -lt 12 ]
then
mess="Good Morning $LOGNAME, Have nice day!"
fi

if [ $temph -gt 12 -a $temph -le 16 ]
then
mess="Good Afternoon $LOGNAME"
fi

if [ $temph -gt 16 -a $temph -le 18 ]
then
mess="Good Evening $LOGNAME"
fi

if which dialog > /dev/null
then
dialog --backtitle "Linux Shell Script Tutorial"\
--title "(-: Welcome to Linux :-)"\
--infobox "\n$mess\nThis is $dat" 6 60
echo -n " Press a key to continue. . . "
read
clear
else
echo -e "$mess\nThis is $dat"
fi
Practical Guide to Linux Commands, Editors, and Shell Programming, A (2nd Edition)
-------------------------------------------------------------------------------------------------------------
Problem : How to write script, that will print, Message "Hello World" , in Bold and Blink effect, and in different colors like red, brown etc using echo command.

Solution : 


# Syntax: echo -e "escape-code your message, var1, var2 etc"
# For eg. echo -e "\033[1m Hello World"
#                               |                  |
#                               |                  |
#                       Escape code    Message
#

clear
echo -e "\033[1m Hello World"
# bold effect
echo -e "\033[5m Blink"
# blink effect
echo -e "\033[0m Hello World"
# back to noraml

echo -e "\033[31m Hello World"
# Red color
echo -e "\033[32m Hello World"
# Green color
echo -e "\033[33m Hello World"
# See remaing on screen
echo -e "\033[34m Hello World"
echo -e "\033[35m Hello World"
echo -e "\033[36m Hello World"

echo -e -n "\033[0m "
# back to noraml

echo -e "\033[41m Hello World"
echo -e "\033[42m Hello World"
echo -e "\033[43m Hello World"
echo -e "\033[44m Hello World"
echo -e "\033[45m Hello World"
echo -e "\033[46m Hello World"


echo -e "\033[0m Hello World"
# back to noraml
Classic Shell Scripting
-------------------------------------------------------------------------------------------------------------
Problem : Write script to implement background process that will continually print current time in upper right corner of the screen , while user can do his/her normal job at $ prompt.

Solution : 

echo
echo "Digital Clock for Linux"
echo "To stop this clock use command kill pid, see above for pid"
echo "Press a key to continue. . ."

while :
do
ti=`date +"%r"`
echo -e -n "\033[7s" #save current screen postion & attributes
#
# Show the clock
#

tput cup 0 69 # row 0 and column 69 is used to show clock

echo -n $ti # put clock on screen

echo -e -n "\033[8u" #restore current screen postion & attributs
#
#Delay fro 1 second
#
sleep 1
done

Thursday, December 2, 2010

Database in Linux

Follow the instruction to create database and tabel in mysql.

Go to terminal with root.
Assuming you have installed mysql in your linux version and no password for accessing mysql.
#mysql -u root
mysql> create database new;
Query OK, 1 row effected (0.02 Sec)
mysql> use new;
database changed
mysql>create table emp_data(EMP_NO varchar(10),EMP_NAME varchar(30),EMP_ADDRESS varchar(60),EMP_AGE varchar(3),EMP_GENDER varchar(6),EMP_DESIGNATION varchar(15),EMP_BASIC_SALARYvarchar(10));

TABLE CREATED SUCCESSFULLY.

Saturday, November 6, 2010

Auto Shutdown or programmed poweroff

There are some times when you need to turn automatically your PC off, there can be a lot of examples when this is necessary.
I usually do this when I left some torrent downloading, let’s say some Linux isos to test a new Linux distribution, so I leave my PC downloading the ISO at office over the weekend, and program my PC to turn of, some two or three hours after the estimated time when the download is suppose do finish.
I do not have too much bandwidth so a whole DVD can take some 26 hours downloading. Specially because I limit the usages of bandwidth to 50% of the available to leave room for other tasks.
Well, let’s see how to do it.
sudo shutdown -h -P [hour]:[minutes]
This is only useful, if you need to shutdown the computer on the same day you are, or the next one, let’s suppose it is noon, and you want to shutdown your computer at 17 hours.
sudo shutdown -h -P 17:00
But if you need to shutdown your computer the day after tomorrow, or even later, use this commands.
sleep 2d 3h | poweroff
You need to run that command as root, or using sudo, but you need to be in thesudoers file, and not required to enter passwords.
That command is going to shutdown the computer after 2 days and 3 hours from now
I am sure there are some other ways to program the shutdown of a Linux computer, and I will be glad if you can post alternatives in the comments.

Monday, October 4, 2010

Adding User in Linux with Script

Create a File contains the username on each line. (userlist.txt)


#ADD USER


for i in `more userlist.txt `

do
echo $i
adduser $i
done


Remove shadow  file and create it again using 


  pwconv


That utility will reconcile all of the user accounts listed in the passwd file with the shadow file entries. Then you can use the passwd utility to create a passwd for the new user account.

#CHANGE THE PASSWORD

for i in `more userlist.txt `
do
echo $i
echo $i"123" | passwd –-stdin "$i"
echo; echo "User $username’s password changed!"
done

#FORCE TO CHANGE PASSWORD AT FIRST LOGIN

for i in `more userlist.txt `
do
echo $i
echo $i"123" | chage -d 0 --stdin "$i"
echo; echo "User $username’s password changed!"
done

Tuesday, April 20, 2010

10 Tools to add beauty in SHELL SCRIPT..............


There are some misconceptions that shell scripts are only for a CLI environment. You can easily use various tools to write GUI and/or network (socket) scripts under KDE or Gnome desktops. Shell scripts can make use of some of the GUI widget (menus, warning boxs, progress bars etc). You can always control the final output, cursor position on screen, various output effects, and so on. With the following tools you can build powerful, interactive, user friendly UNIX / Linux bash shell scripts.
Creating GUI application is not just expensive task but task that takes time and patience. Luckily, both UNIX and Linux ships with plenty of tools to write beautiful GUI scripts. The following tools are tested on FreeBSD and Linux operating systems but should work under other UNIX like operating systems.

#1: notify-send Command

The notify-send command allows you to send desktop notifications to the user via a notification daemon from the command line. This is useful to inform the desktop user about an event or display some form of information without getting in the user's way. You need to install the following package:
$ sudo apt-get install libnotify-bin
In this example, send simple desktop notification from the command line, enter:
 
notify-send "rsnapshot done :)"
 
Sample outputs:
Fig:01: notify-send in action
Fig:01: notify-send in action

Here is another code with additional options:
 
....
alert=18000
live=$(lynx --dump http://money.rediff.com/ | grep 'BSE LIVE' | awk '{ print $5}' | sed 's/,//g;s/\.[0-9]*//g')
[ $notify_counter -eq 0 ] && [ $live -ge $alert ] && { notify-send -t 5000 -u low -i   "BSE Sensex touched 18k";  notify_counter=1; }
...
Sample outputs:
Fig.02: notify-send with timeouts and other options
Fig.02: notify-send with timeouts and other options

Where,
  • -t 5000: Specifies the timeout in milliseconds ( 5000 milliseconds = 5 seconds)
  • -u low : Set the urgency level (i.e. low, normal, or critical).
  • -i gtk-dialog-info : Set an icon filename or stock icon to display (you can set path as -i /path/to/your-icon.png).
For more information on use of the notify-send utility, please refer to the notify-send man page, viewable by typing man notify-send from the command line:
man notify-send

#2: tput Command

The tput command is used to set terminal features. With tput you can set:
  • Move the cursor around the screen.
  • Get information about terminal.
  • Set colors (background and foreground).
  • Set bold mode.
  • Set reverse mode and much more.
Here is a sample code:
#!/bin/bash
 
# clear the screen
tput clear
 
# Move cursor to screen location X,Y (top left is 0,0)
tput cup 3 15
 
# Set a foreground colour using ANSI escape
tput setaf 3
echo "XYX Corp LTD."
tput sgr0
 
tput cup 5 17
# Set reverse video mode
tput rev
echo "M A I N - M E N U"
tput sgr0
 
tput cup 7 15
echo "1. User Management"
 
tput cup 8 15
echo "2. Service Management"
 
tput cup 9 15
echo "3. Process Management"
 
tput cup 10 15
echo "4. Backup"
 
# Set bold mode
tput bold
tput cup 12 15
read -p "Enter your choice [1-4] " choice
 
tput clear
tput sgr0
tput rc
Sample outputs:
Fig.03: tput in action
Fig.03: tput in action

For more detail concerning the tput command, see the following man page:
man 5 terminfo
man tput

#3: setleds Command

The setleds command allows you to set the keyboard leds. In this example, set NumLock on:
setleds -D +num
To turn it off NumLock, enter:
setleds -D -num
  • -caps : Clear CapsLock.
  • +caps : Set CapsLock.
  • -scroll : Clear ScrollLock.
  • +scroll : Set ScrollLock.
See setleds command man page for more information and options:
man setleds

#4: zenity Command

The zenity commadn will display GTK+ dialogs box, and return the users input. This allows you to present information, and ask for information from the user, from all manner of shell scripts. Here is a sample GUI client for the whois directory service for given domain name:
#!/bin/bash
# Get domain name
_zenity="/usr/bin/zenity"
_out="/tmp/whois.output.$$"
domain=$(${_zenity} --title  "Enter domain" \
             --entry --text "Enter the domain you would like to see whois info" )
 
if [ $? -eq 0 ]
then
  # Display a progress dialog while searching whois database
  whois $domain  | tee >(${_zenity} --width=200 --height=100 \
          --title="whois" --progress \
               --pulsate --text="Searching domain info..." \
                                    --auto-kill --auto-close \
                                    --percentage=10) >${_out}
 
  # Display back output
  ${_zenity} --width=800 --height=600  \
      --title "Whois info for $domain" \
      --text-info --filename="${_out}"
else
  ${_zenity} --error \
      --text="No input provided"
fi
Sample outputs:
Fig.04: zenity in Action
Fig.04: zenity in Action

See the zenity man page for more information and all other supports GTK+ widgets:
zenity --help
man zenity

#5: kdialog Command

kdialog is just like zenity but it is designed for KDE desktop / qt apps. You can display dialogs using kdialog. The following will display message on screen:
 
kdialog --dontagain myscript:nofilemsg --msgbox "File: '~/.backup/config' not found."
 
Sample outputs:
Fig.05: Suppressing the display of a dialog
Fig.05: Suppressing the display of a dialog
See shell scripting with KDE Dialogs tutorial for more information.

#6: Dialog

Dialog is an application used in shell scripts which displays text user interface widgets. It uses the curses or ncurses library. Here is a sample code:
>#!/bin/bash
dialog --title "Delete file" \
--backtitle "Linux Shell Script Tutorial Example" \
--yesno "Are you sure you want to permanently delete \"/tmp/foo.txt\"?" 7 60
 
# Get exit status
# 0 means user hit [yes] button.
# 1 means user hit [no] button.
# 255 means user hit [Esc] key.
response=$?
case $response in
   0) echo "File deleted.";;
   1) echo "File not deleted.";;
   255) echo "[ESC] key pressed.";;
esac
See the dialog man page for details:
man dialog

A Note About Other User Interface Widgets Tools

UNIX and Linux comes with lots of other tools to display and control apps from the command line, and shell scripts can make use of some of the KDE / Gnome / X widget set:
  • gmessage - a GTK-based xmessage clone.
  • xmessage - display a message or query in a window (X-based /bin/echo)
  • whiptail - display dialog boxes from shell scripts
  • python-dialog - Python module for making simple Text/Console-mode user interfaces

#7: logger command

The logger command writes entries in the system log file such as /var/log/messages. It provides a shell command interface to the syslog system log module:
 
logger "MySQL database backup failed."
tail -f /var/log/messages
logger -t mysqld -p daemon.error "Database Server failed"
tail -f /var/log/syslog
 
Sample outputs:
Apr 20 00:11:45 vivek-desktop kernel: [38600.515354] CPU0: Temperature/speed normal
Apr 20 00:12:20 vivek-desktop mysqld: Database Server failed
See howto write message to a syslog / log file for more information. Alternatively, you can see the logger man page for details:
man logger

#8: setterm Command

The setterm command can set various terminal attributes. In this example, force screen to turn black in 15 minutes. Monitor standby will occur at 60 minutes:
 
setterm -blank 15 -powersave powerdown -powerdown 60
 
In this example show underlined text for xterm window:
 
setterm -underline on;
echo "Add Your Important Message Here"
setterm -underline off
 
Another useful option is to turn on or off cursor:
 
setterm -cursor off
 
Turn it on:
 
setterm -cursor on
 
See the setterm command man page for details:
man setterm

#9: smbclient: Sending Messages To MS-Windows Workstations

The smbclient command can talk to an SMB/CIFS server. It can send a message to selected users or all users on MS-Windows systems:
smbclient -M WinXPPro <1
Message 2
...
..
EOF
OR
 
echo "${Message}" | smbclient -M salesguy2
 
See smbclient man page or read our previous post about "sending a message to Windows Workstation" with smbclient command:
man smbclient

#10: Bash Socket Programming

Under bash you can open a socket to pass some data through it. You don't have to use curl or lynx commands to just grab data from remote server. Bash comes with two special device files which can be used to open network sockets. From the bash man page:
  1. /dev/tcp/host/port - If host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts to open a TCP connection to the corresponding socket.
  2. /dev/udp/host/port - If host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts to open a UDP connection to the corresponding socket.
You can use this technquie to dermine if port is open or closed on local or remote server without using nmap or other port scanner:
# find out if TCP port 25 open or not
(echo >/dev/tcp/localhost/25) &>/dev/null && echo "TCP port 25 open" || echo "TCP port 25 close"
You can use bash loop and find out open ports with the snippets:
 
echo "Scanning TCP ports..."
for p in {1..1023}
do
  (echo >/dev/tcp/localhost/$p) >/dev/null 2>&1 && echo "$p open"
done
Sample outputs:
Scanning TCP ports...
22 open
53 open
80 open
139 open
445 open
631 open
In this example, you bash script act as an HTTP client:
#!/bin/bash
exec 3<> /dev/tcp/${1:-www.cyberciti.biz}/80
 
printf "GET / HTTP/1.0\r\n" >&3
printf "Accept: text/html, text/plain\r\n" >&3
printf "Accept-Language: en\r\n" >&3
printf "User-Agent: nixCraft_BashScript v.%s\r\n" "${BASH_VERSION}"   >&3
printf "\r\n" >&3
 
while read LINE <&3
do
   # do something on $LINE
   # or send $LINE to grep or awk for grabbing data
   # or simply display back data with echo command
   echo $LINE
done
See the bash man page for more information:
man bash

A Note About GUI Tools and Cronjob

You need to request local display/input service using export DISPLAY=[user's machine]:0 command if you are using cronjob to call your scripts. For example, call /home/vivek/scripts/monitor.stock.sh as follows which uses zenity tool:
@hourly DISPLAY=:0.0 /home/vivek/scripts/monitor.stock.sh
Have a favorite UNIX tool to spice up shell script? Share it in the comments below.