Sunday, August 14, 2011

Some Scripting Tricks

. . .Uses of some Build in Variables. . .

1. echo $LOGNAME and echo $USER -----> show's who is the logged in user
2. echo $HOSTNAME               -----> show's the Hostname of the Linux Box
3. echo $PPID  ----> show's the Process ID of Shell's Parent Directory ( If u kill this every logged in terminal will be closed)
4. echo $PWD            ----> show's the Present Working Directory
5. echo $UID              -----> show's the UserID of the currently Logged in user
6. echo $MAIL          -----> Show's the Mail Path       
7. echo $HISTFILE   -----> Show's the file's which stores the history details
8. echo $HOME        -----> show's the users HOME Directory
9. echo $PATH         -----> A colon-separated list of directories in which the shell looks for commands.
10.echo $BASH The full pathname used to execute the current instance of Bash.
11.echo $HISTSIZE  ----> This will show you the HISTORY size
12  $?   ------> Expands to the exit status of the most recently executed foreground pipeline.
13. $$   -----> Shows to the process ID of the shell and if it used inside a script it shows the process ID of the script.
14. $!   -----> Expands to the process ID of the most recently executed background command(&).
15. $0  -----> Expands to the name of the shell or shell script.
16. $_  -----> It will show you what is the Last Argument used [ like esc (.) or alt (.) ]

How to set a value for a variable in single command?

#echo ${raj:=rajkumar}
#echo $raj

How to assign o/p value of a command to a variable?
Syntax:

1. $(command)
2. `command`

#echo `date`
Sun May 1 13:12:31 IST 2011
#echo $(date)
Sun May 1 13:12:40 IST 2011

cat first.sh

#!bin/bash
a=`du -sh /home/rajm | awk {'print $1'}`
echo "I am User $USER and I am running this script"
echo "The UserID of $USER is $UID"
echo "The name of the Script is $0"
echo "The processID of the script $0 is: $$"
echo "The Script is running from $PWD directory"
echo "Size of User $LOGNAME Home directory($HOME) is :$a"
echo "Status of Previously executed command is: $?"
echo "The script $0 contains $LINENO Lines"

#sh first.sh
I am User rajm and I am running this script
The UserID of rajm is 516
The name of the Script is first.sh
The processID of the script first.sh is: 5096
The Script is running from /home/rajm/script/blog directory
Size of User rajm Home directory(/home/rajm) is :696M
Status of Previously executed command is: 0
The script first.sh contains 10 Lines