Friday, April 10, 2009

Basic shell programming commands quote, exit, read

About Quotes
In shell programming you might want to use frequently three types of quotes.

1)Double Quotes ("") : Anything you write inside double quotes that is treated as themselves except dollar sign ($) and backslash (\).

2)Single Quotes (') : Anything you write inside double quotes that is treated as themselves. All remain unchanged.

3)Back Quotes (`) : Back quote is used to execute commands. If we want to execute any command inside shell script that must be inside back quotes.

Below is an example with these three types of quote.

Tahaa2:/home/arju/test# cat t_quote.sh
variable=10
echo "This is variable $variable"
echo 'This is variable $variable'
echo "This is pwd `pwd`"

Tahaa2:/home/arju/test# chmod +x t_quote.sh
Tahaa2:/home/arju/test# ./t_quote.sh
This is variable 10
This is variable $variable
This is pwd /home/arju/test

In the example note that in case of double quotes(") value of variable is shown but in case of single quotes(') variable name itself shown as it was inside single quotes. And for backquotes `pwd` command is executed and shown on the console.

Exit status $?
After every command or shell script executed on linux, it always returns the status of the command whether command is executed successfully or not. If command is executed sucessfully then exit status become zero, but if command is not executed successfully then exit status become non-zero value. We can check the exit status by $? sign.
Below is an example:

Tahaa2:/home/arju/test# ls nofile.txt
ls: nofile.txt: No such file or directory
Tahaa2:/home/arju/test# echo $?
2

Tahaa2:/home/arju/test# rm nofileexist.txt no_file.bat
rm: cannot lstat `nofileexist.txt': No such file or directory
rm: cannot lstat `no_file.bat': No such file or directory
Tahaa2:/home/arju/test# echo $?
1

Tahaa2:/home/arju/test# echo $?
0

Read data from console
With the "read" statement you can read input data from keyboard and store it in variable. Later you can process, work and display this variable.
Below is an example of read.
Tahaa2:/home/arju/test# vi t_read.sh
echo -n "Please eneter your name: "
read name
echo "Welcome $name to the http://arjudba.blogspot.com "
Tahaa2:/home/arju/test# chmod +x t_read.sh
Tahaa2:/home/arju/test# ./t_read.sh
Please eneter your name: Robert
Welcome Robert to the http://arjudba.blogspot.com

Related Documents
http://arjudba.blogspot.com/2009/04/rules-for-naming-variable-name-in-unix.html
http://arjudba.blogspot.com/2009/04/arithmatic-operation-and-expression-in.html

No comments:

Post a Comment