ase and esac are control structures in shell scripts that are used to define a case statement.
Here’s an example of how you can use a case statement in a shell script:
case $VAR in
value1)
# do something
;;
value2)
# do something else
;;
*)
# do something else
;;
esac
In this example, the case statement checks the value of the variable $VAR. If the value is value1, the script will execute the commands in the first block. If the value is value2, the script will execute the commands in the second block. If the value is anything else, the script will execute the commands in the third block (the default case, indicated by the *).
The ;; at the end of each block indicates the end of the case.
I hope this helps! Let me know if you have any questions.
To write your first shell script, you will need to use a text editor to create a new file. You can use any text editor that you like, such as vi, nano, or gedit.
Here is an example of a simple shell script that displays the message “Hello, World!” on the screen:
#!/bin/bash
echo "Hello, World!"
To make the script executable, you will need to give it execute permissions using the chmod command:
chmod +x myscript.sh
You can then run the script by typing its name:
./myscript.sh
This will execute the commands in the script and display the message “Hello, World!” on the screen.
Here is a brief explanation of the lines in the script:
The first line, #!/bin/bash, is called the shebang line. It tells the system which interpreter to use to execute the script. In this case, it is telling the system to use the bash shell to execute the script.
The second line, echo "Hello, World!", is a command that displays the message “Hello, World!” on the screen. The echo command is a built-in command in the bash shell that prints its arguments to the standard output.
I hope this helps! Let me know if you have any questions.
In this post, we will discuss in detail about the Unix environment. An important Unix concept is the environment, which is defined by environment variables. Some are set by the system, others by user, yet others by the shell, or any program that loads another program.
A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.
For example, first we set a variable TEST and then we access its value using the echo command −
$VAR="Sample String"
$echo $VAR
It produces the following result.
Sample String
Note that the environment variables are set without using the $ sign but while accessing them we use the $ sign as prefix. These variables retain their values until we come out of the shell.
When you log in to the system, the shell undergoes a phase called initialization to set up the environment. This is usually a two-step process that involves the shell reading the following files −
/etc/profile
profile
The process is as follows −
The shell checks to see whether the file /etc/profile exists.
If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed.
The shell checks to see whether the file .profile exists in your home directory. Your home directory is the directory that you start out in after you log in.
If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed.
As soon as both of these files have been read, the shell displays a prompt −
$
This is the prompt where you can enter commands in order to have them executed.
Note − The shell initialization process detailed here applies to all Bourne type shells, but some additional files are used by bash and ksh.
The .profile File
The file /etc/profile is maintained by the system administrator of your Unix machine and contains shell initialization information required by all users on a system.
The file .profile is under your control. You can add as much shell customization information as you want to this file. The minimum set of information that you need to configure includes −
The type of terminal you are using.
A list of directories in which to locate the commands.
A list of variables affecting the look and feel of your terminal.
You can check your .profile available in your home directory. Open it using the vi editor and check all the variables set for your environment.
Setting the Terminal Type
Usually, the type of terminal you are using is automatically configured by either the login or getty programs. Sometimes, the auto-configuration process guesses your terminal incorrectly.
If your terminal is set incorrectly, the output of the commands might look strange, or you might not be able to interact with the shell properly.
To make sure that this is not the case, most users set their terminal to the lowest common denominator in the following way −
$TERM=vt100
$
Setting the PATH
When you type any command on the command prompt, the shell has to locate the command before it can be executed.
The PATH variable specifies the locations in which the shell should look for commands. Usually the Path variable is set as follows −
$PATH=/bin:/usr/bin
$
Here, each of the individual entries separated by the colon character (:) are directories. If you request the shell to execute a command and it cannot find it in any of the directories given in the PATH variable, a message similar to the following appears −
$hello
hello: not found
$
There are variables like PS1 and PS2 which are discussed in the next section.
PS1 and PS2 Variables
The characters that the shell displays as your command prompt are stored in the variable PS1. You can change this variable to be anything you want. As soon as you change it, it’ll be used by the shell from that point on.
For example, if you issued the command −
$PS1='=>'
=>
=>
=>
Your prompt will become =>. To set the value of PS1 so that it shows the working directory, issue the command −
=>PS1="[\u@\h \w]\$"
The result of this command is that the prompt displays the user’s username, the machine’s name (hostname), and the working directory.
There are quite a few escape sequences that can be used as value arguments for PS1; try to limit yourself to the most critical so that the prompt does not overwhelm you with information.
Sr.No.
Escape Sequence & Description
1
\t
Current time, expressed as HH:MM:SS
2
\d
Current date, expressed as Weekday Month Date
3
\n
Newline
4
\s
Current shell environment
5
\W
Working directory
6
\w
Full path of the working directory
7
\u
Current user’s username
8
\h
Hostname of the current machine
9
\#
Command number of the current command. Increases when a new command is entered
10
\$
If the effective UID is 0 (that is, if you are logged in as root), end the prompt with the # character; otherwise, use the $ sign
You can make the change yourself every time you log in, or you can have the change made automatically in PS1 by adding it to your .profile file.
When you issue a command that is incomplete, the shell will display a secondary prompt and wait for you to complete the command and hit Enteragain.
The default secondary prompt is > (the greater than sign), but can be changed by re-defining the PS2 shell variable −
Following is the example which uses the default secondary prompt −
$ echo "this is a
> test"
this is a
test
$
The example given below re-defines PS2 with a customized prompt −
$ PS2="secondary prompt->"
$ echo "this is a
secondary prompt->test"
this is a
test
$
Environment Variables
Following is the partial list of important environment variables. These variables are set and accessed as mentioned below −
Certainly, here’s the data formatted into a three-column table with “Sr. No.,” “Variable,” and “Description” columns:
Sr. No.
Variable
Description
1
DISPLAY
Contains the identifier for the display that X11 programs should use by default.
2
HOME
Indicates the home directory of the current user: the default argument for the cd built-in command.
3
IFS
Indicates the Internal Field Separator that is used by the parser for word splitting after expansion.
4
LANG
LANG expands to the default system locale; LC_ALL can be used to override this. For example, if its value is pt_BR, then the language is set to (Brazilian) Portuguese and the locale to Brazil.
5
LD_LIBRARY_PATH
A Unix system with a dynamic linker, contains a colon-separated list of directories that the dynamic linker should search for shared objects when building a process image after exec, before searching in any other directories.
6
PATH
Indicates the search path for commands. It is a colon-separated list of directories in which the shell looks for commands.
7
PWD
Indicates the current working directory as set by the cd command.
8
RANDOM
Generates a random integer between 0 and 32,767 each time it is referenced.
9
SHLVL
Increments by one each time an instance of bash is started. This variable is useful for determining whether the built-in exit command ends the current session.
10
TERM
Refers to the display type.
11
TZ
Refers to Time zone. It can take values like GMT, AST, etc.
12
UID
Expands to the numeric user ID of the current user, initialized at the shell startup.
Now, the data is organized into a three-column table with “Sr. No.,” “Variable,” and “Description” columns for better readability and understanding.
Following is the sample example showing a few environmental variables −
A shell maintains an environment that includes a set of variables defined by the login program, the system initialization file, and the user initialization files. In addition, some variables are defined by default.
A shell can have two types of variables:
Environment variables – Variables that are exported to all processes spawned by the shell. Their settings can be seen with the env command. A subset of environment variables, such as PATH, affects the behavior of the shell itself.
Shell (local) variables – Variables that affect only the current shell. In the C shell, a set of these shell variables have a special relationship to a corresponding set of environment variables. These shell variables are user, term, home, and path. The value of the environment variable counterpart is initially used to set the shell variable.
In the C shell, you use the lowercase names with the set command to set shell variables. You use uppercase names with the setenv command to set environment variables. If you set a shell variable, the shell sets the corresponding environment variable. Likewise, if you set an environment variable, the corresponding shell variable is also updated. For example, if you update the path shell variable with a new path, the shell also updates the PATH environment variable with the new path.
In the Bourne and Korn shells, you can use the uppercase variable name equal to some value to set both shell and environment variables. You also have to use the export command to activate the variables for any subsequently executed commands.
For all shells, you generally refer to shell and environment variables by their uppercase names.
In a user initialization file, you can customize a user’s shell environment by changing the values of the predefined variables or by specifying additional variables. The following table shows how to set environment variables in a user initialization file.Table 4–18 Setting Environment Variables in a User Initialization File
Shell Type
Line to Add to the User Initialization File
C shell
setenvVARIABLEvalueExample:setenv MAIL /var/mail/ripley
Bourne or Korn shell
VARIABLE=value; exportVARIABLEExample: MAIL=/var/mail/ripley;export MAIL
The following table describes environment variables and shell variables that you might want to customize in a user initialization file. For more information about variables that are used by the different shells, see the sh(1), ksh(1), or csh(1) man pages.Table 4–19 Shell and Environment Variable Descriptions
Variable
Description
CDPATH, or cdpath in the C shell
Sets a variable used by the cd command. If the target directory of the cd command is specified as a relative path name, the cd command first looks for the target directory in the current directory (“.”). If the target is not found, the path names listed in the CDPATH variable are searched consecutively until the target directory is found and the directory change is completed. If the target directory is not found, the current working directory is left unmodified. For example, the CDPATH variable is set to /home/jean, and two directories exist under /home/jean, bin, and rje. If you are in the /home/jean/bin directory and type cd rje, you change directories to /home/jean/rje, even though you do not specify a full path.
history
Sets the history for the C shell.
HOME, or home in the C shell
Sets the path to the user’s home directory.
LANG
Sets the locale.
LOGNAME
Defines the name of the user currently logged in. The default value of LOGNAME is set automatically by the login program to the user name specified in the passwd file. You should only need to refer to, not reset, this variable.
LPDEST
Sets the user’s default printer.
MAIL
Sets the path to the user’s mailbox.
MANPATH
Sets the hierarchies of man pages that are available.
PATH, or path in the C shell
Specifies, in order, the directories that the shell searches to find the program to run when the user types a command. If the directory is not in the search path, users must type the complete path name of a command. As part of the login process, the default PATH is automatically defined and set as specified in .profile (Bourne or Korn shell) or .cshrc (C shell).The order of the search path is important. When identical commands exist in different locations, the first command found with that name is used. For example, suppose that PATH is defined in Bourne and Korn shell syntax as PATH=/bin:/usr/bin:/usr/sbin:$HOME/bin and a file named sample resides in both /usr/bin and /home/jean/bin. If the user types the command sample without specifying its full path name, the version found in /usr/bin is used.
prompt
Defines the shell prompt for the C shell.
PS1
Defines the shell prompt for the Bourne or Korn shell.
SHELL, or shell in the C shell
Sets the default shell used by make, vi, and other tools.
TERMINFO
Specifies the path name for an unsupported terminal that has been added to the terminfo file. Use the TERMINFO variable in either the /etc/profile or /etc/.login file. When the TERMINFO environment variable is set, the system first checks the TERMINFO path defined by the user. If the system does not find a definition for a terminal in the TERMINFO directory defined by the user, it searches the default directory, /usr/share/lib/terminfo, for a definition. If the system does not find a definition in either location, the terminal is identified as “dumb.”
TERM, or term in the C shell
Defines the terminal. This variable should be reset in either the /etc/profile or /etc/.login file. When the user invokes an editor, the system looks for a file with the same name that is defined in this environment variable. The system searches the directory referenced by TERMINFO to determine the terminal characteristics.
TZ
Sets the time zone. The time zone is used to display dates, for example, in the ls -l command. If TZ is not set in the user’s environment, the system setting is used. Otherwise, Greenwich Mean Time is used.
There are total 3 types of looping statements that can be used in bash programming
while statement
for statement
until statement
To control the flow of the loop, two control statements are used they are,
break
continue
Their descriptions and syntax are as follows:
while statement
Here the command is evaluated and based on the resulting loop will be executed, if the command raises to false then the loop will be terminated
for statement
The for loop operates on lists of items. It repeats a set of commands for every item in a list. Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN.
until statement
The until loop is executed as many times as the condition/command evaluates to false. The loop terminates when the condition/command becomes true.
In this post, we will learn how to use inbuild special symbols in the shell to make our code simple. Let’s assume we have a file in the temp directory and we will use the inbuilt keyword to test the functionality.
We have 2 files in the Desktop
The ls command shows all the files in the current directory.
root@vps43086554:~/Desktop# ls sample.sh sample.txt root@vps43086554:~/Desktop#
Now will make a simple shell script sample.sh where we will write an if condition where the condition will check with the help of existing keywords.
if [ -e sample.txt ]; then echo “Inside if ture part” fi
In the above the if condition we have written an if the condition where we have written -e and a file name.
File Operators
-e
Ture if file exists. Menas it will check if the file exists in the directory then it will return true.
Prerequisite -Create 2 files sample.sh sample.txt
if [ -e sample.txt ]; then echo “Inside if ture part” fi
Output- root@vps43086554:~/Desktop# sh sample.sh Inside if ture part root@vps43086554:~/Desktop#
-d
True if the file is a directory.
Prerequisite- Create a folder named a folder.
Code to create a folder named as folder.
root@vps43086554:~/Desktop# mkdir folder root@vps43086554:~/Desktop# ls folder sample.sh sample.txt
Code to check the folder is exists or not.
if [ -e folder ]; then echo “Inside if ture part” fi
Output
root@vps43086554:~/Desktop# sh sample.sh Inside if ture part
-f
True if the file exists and the file is a regular file.
Prerequisite- Create an invalid file named non_normarl.gfd.
Code-
if [ -f non_normal.gfd ]; then echo “Inside if ture part” fi if [ -f sample.txt ]; then echo “Inside if ture part of valid file” fi
root@vps43086554:~/Desktop# sh sample.sh Inside if ture part of valid file
Linux has many commands available which can be very useful. Even it is very powerful when it gets all the available parameters along with the commands. Due to the varsity of the commands available in the Linux, it’s difficult to remember all the commands.
How to use –h or –help?
Launch the terminal by pressing Ctrl+ Alt+ T or just click on the terminal icon in the taskbar. Simply type your command whose usage you to know in the terminal with –h or –help after space and press enter. And you’ll get the complete usage of that command as shown below.
Description
help displays brief summaries of shell builtin commands. If PATTERN is specified, gives detailed help on all commands matching PATTERN, otherwise the list of help topics is printed.
Syntax
help [-dms] [PATTERN ...]
Options
-d
Output short description for each topic.
-m
Display usage in pseudo-manpage format.
-s
Output only a short usage synopsis for each topic matching.
Examples
help echo
Display a brief description of the builtin shell command echo.
Linux man command
The “man” is a short term for manual page. In unix like operating systems such as linux, man is an interface to view the system’s reference manual.
A user can request to display a man page by simply typing man followed by a space and then argument. Here its argument can be a command, utility or function. A manual page associated with each of these arguments is displayed.
If you will provide a section number in the command, then man will be directed to look into that section number of the manual and that section page will be displayed. And if not, then by default it will display the first page and you have to go through the entire sections in a pre-defined manner.
We’ll read about section number in this tutorial.
Syntax of man:
man [option(s)] keyword(s)
But generally [option(s)] are not used. Only keyword is written as an argument.
For example,
man ls
This command will display all the information about ‘ls’ command as shown in the screenshot.
info command in Linux with Examples
infocommand reads documentation in the info format. It will give detailed information for a command when compared with the man page. The pages are made using the texinfo tools because of which it can link with other pages, create menus and easy navigation.
Syntax:
info [OPTION]... [MENU-ITEM...]
Options:
-a, –all: It use all matching manuals.
-k, –apropos=STRING: It look up STRING in all indices of all manuals.
-d, –directory=DIR: It add DIR to INFOPATH.
-f, –file=MANUAL: It specify Info manual to visit.
-h, –help: It display this help and exit.
-n, –node=NODENAME: It specify nodes in first visited Info file.
-o, –output=FILE: It output selected nodes to FILE.
-O, –show-options, –usage: It go to command-line options node.
-v, –variable VAR=VALUE: It assign VALUE to Info variable VAR.
–version: It display version information and exit.
-w, –where, –location: It print physical location of Info file.
Examples:
-a : It use all matching manuals and displays them for a particular command. info -a cvs
Conditional Statements: There are total 5 conditional statements available in the bash programming,Which can be implemented in the different situation in the bash/shell programming.
if statement
if-else statement
if..elif..else..fi statement (Else If ladder)
if..then..else..if..then..fi..fi..(Nested if)
switch statement
if statement
If statement is the simplest statement in the series.Where it is used to compare the two variable. This block will process if specified condition is true. Syntax:
if [ expression ]
then
statement
fi
if-else statement
If specified condition is not true in if part then else part will be execute.This can be helpful when we have 3 variables and need to compare between Syntax
if [ expression ]
then
statement1
else
statement2
fi
if..elif..else..fi statement (Else If ladder)
We can use to compare more than 3 variables by using this block.To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part. Syntax
if [ expression1 ]
then
statement1
statement2
.
elif [ expression2 ]
then
statement3
statement4
.
else
statement5
fi
if..then..else..if..then..fi..fi..(Nested if)
Generally Nested block is used for comparison of multiple nested conditions. if-else block can be used when, one condition is satisfies then it again checks another condition. In the syntax, if expression1 is false then it processes else part, and again expression2 will be check. Syntax:
if [ expression1 ]
then
statement1
statement2
.
else
if [ expression2 ]
then
statement3
.
fi
fi
switch statement
case statement works as a switch statement if specified value match with the pattern then it will execute a block of that particular pattern When a match is found all of the associated statements until the double semicolon (;;) is executed. A case will be terminated when the last command is executed. If there is no match, the exit status of the case is zero.
Syntax:
case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac
Whatever you can do with a shell script, you can do with Perl and python too or in general any scripting language. However, These languages have advantages and disadvantages over each other.
Here are a few reasons why we use the scripts.
You can write a script to initialize something at the boot time of the system. so you don’t need to do it manually. If you want to run a particular application to run every time when your system boots then you can write a shell script to do this for you Instead of doing it manually it will do it whenever your system starts.
You can write a script that installs per-requisite and build the code with user input to enable/disable some features. If you are a system admin and you need to install some application for your system or virtual machines with n number of machines it will reduce your time to type manually for each system.
To kill or start multiple applications together. If you are a performance Tester and want to run multiple instances of the same applications you can write a script to lunch multiple instances of an application.When you measure the performance.
To observe a large database of files and find some patterns out of it. If you are a database administrator or database tester monitoring the performance of a database in the production environment that 24*7 will be a hectic job. Where is the script that can do your task on behalf of you?
System boot scripts (/etc/init.d)
System administrators, for automating many aspects of computer maintenance, user account creation, etc.
Application package installation tools More detail
Application startup scripts, especially unattended applications (e.g. started from cron or at)
Any user needing to automate the process of setting up and running commercial applications, or their own code.
There are various operators supported by each shell. We will discuss in detail about Bourne shell (default shell) in this chapter.According to the operation performed on the operators it has been classified into the below types.
We will now discuss the following operators −
Arithmetic Operators
Relational Operators
Boolean Operators
String Operators
File Test Operators
Bourne shell didn’t originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr.
The following example shows how to add two numbers −
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"
The above script will generate the following result −
Total value : 4
The following points need to be considered while adding −
There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.
The complete expression should be enclosed between ‘ ‘, called the backtick.
Arithmetic Operators
The following arithmetic operators are supported by Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −
Operator
Description
Example
+ (Addition)
Adds values on either side of the operator
`expr $a + $b` will give 30
– (Subtraction)
Subtracts right hand operand from left hand operand
`expr $a – $b` will give -10
* (Multiplication)
Multiplies values on either side of the operator
`expr $a \* $b` will give 200
/ (Division)
Divides left hand operand by right hand operand
`expr $b / $a` will give 2
% (Modulus)
Divides left hand operand by right hand operand and returns remainder
`expr $b % $a` will give 0
= (Assignment)
Assigns right operand in left operand
a = $b would assign value of b into a
== (Equality)
Compares two numbers, if both are same then returns true.
[ $a == $b ] would return false.
!= (Not Equality)
Compares two numbers, if both are different then returns true.
[ $a != $b ] would return true.
It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect.
All the arithmetical calculations are done using long integers.
Relational Operators
Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for string values unless their value is numeric.
For example, following operators will work to check a relation between 10 and 20 as well as in between “10” and “20” but not in between “ten” and “twenty”.
Assume variable a holds 10 and variable b holds 20 then −
Operator
Description
Example
-eq
Checks if the value of two operands are equal or not; if yes, then the condition becomes true.
[ $a -eq $b ] is not true.
-ne
Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true.
[ $a -ne $b ] is true.
-gt
Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.
[ $a -gt $b ] is not true.
-lt
Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.
[ $a -lt $b ] is true.
-ge
Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.
[ $a -ge $b ] is not true.
-le
Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true.
[ $a -le $b ] is true.
It is very important to understand that all the conditional expressions should be placed inside square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect.
Boolean Operators
The following Boolean operators are supported by the Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −
Operator
Description
Example
!
This is logical negation. This inverts a true condition into false and vice versa.
[ ! false ] is true.
-o
This is logical OR. If one of the operands is true, then the condition becomes true.
[ $a -lt 20 -o $b -gt 100 ] is true.
-a
This is logical AND. If both the operands are true, then the condition becomes true otherwise false.
[ $a -lt 20 -a $b -gt 100 ] is false.
String Operators
The following string operators are supported by Bourne Shell.
Assume variable a holds “abc” and variable b holds “efg” then −
Operator
Description
Example
=
Checks if the value of two operands are equal or not; if yes, then the condition becomes true.
[ $a = $b ] is not true.
!=
Checks if the value of two operands are equal or not; if values are not equal then the condition becomes true.
[ $a != $b ] is true.
-z
Checks if the given string operand size is zero; if it is zero length, then it returns true.
[ -z $a ] is not true.
-n
Checks if the given string operand size is non-zero; if it is nonzero length, then it returns true.
[ -n $a ] is not false.
str
Checks if str is not the empty string; if it is empty, then it returns false.
[ $a ] is not false.
File Test Operators
We have a few operators that can be used to test various properties associated with a Unix file.
Assume a variable file holds an existing file name “test” the size of which is 100 bytes and has read, write and execute permission on −
Operator
Description
Example
-b file
Checks if file is a block special file; if yes, then the condition becomes true.
[ -b $file ] is false.
-c file
Checks if file is a character special file; if yes, then the condition becomes true.
[ -c $file ] is false.
-d file
Checks if file is a directory; if yes, then the condition becomes true.
[ -d $file ] is not true.
-f file
Checks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes true.
[ -f $file ] is true.
-g file
Checks if file has its set group ID (SGID) bit set; if yes, then the condition becomes true.
[ -g $file ] is false.
-k file
Checks if file has its sticky bit set; if yes, then the condition becomes true.
[ -k $file ] is false.
-p file
Checks if file is a named pipe; if yes, then the condition becomes true.
[ -p $file ] is false.
-t file
Checks if file descriptor is open and associated with a terminal; if yes, then the condition becomes true.
[ -t $file ] is false.
-u file
Checks if file has its Set User ID (SUID) bit set; if yes, then the condition becomes true.
[ -u $file ] is false.
-r file
Checks if file is readable; if yes, then the condition becomes true.
[ -r $file ] is true.
-w file
Checks if file is writable; if yes, then the condition becomes true.
[ -w $file ] is true.
-x file
Checks if file is executable; if yes, then the condition becomes true.
[ -x $file ] is true.
-s file
Checks if file has size greater than 0; if yes, then condition becomes true.
[ -s $file ] is true.
-e file
Checks if file exists; is true even if file is a directory but exists.
In the last post we learned how to declare variables and how to naming conventions.Where we can only use the “_” underscore symbol in the variable name.Where excluding “_” symbol we can not able to use other symbol. This is because those characters are used in the names of special Unix variables. These variables are reserved for specific functions.
For example, the $ character represents the process ID number, or PID, of the current shell −
$echo $$
The above command writes the PID of the current shell −
29949
The following table shows a number of special variables that you can use in your shell scripts −
Sr.No.
Variable & Operations
1
$0 : The filename of the current script.
2
$n : These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).
3
$# : The number of arguments supplied to a script.
4
$* : All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.
5
$@ : All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.
6
$? : The exit status of the last command executed.
7
$$ : The process number of the current shell. For shell scripts, this is the process ID under which they are executing.
8
$! : The process number of the last background command.
Command-Line Arguments
The command-line arguments $1, $2, $3, …$9 are positional parameters, with $0 pointing to the actual command, program, shell script, or function and $1, $2, $3, …$9 as the arguments to the command.
Following script uses various special variables related to the command line −
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
Special Parameters $* and $@
There are special parameters that allow accessing all the command-line arguments at once. $* and $@ both will act the same unless they are enclosed in double quotes, “”.
Both the parameters specify the command-line arguments. However, the “$*” special parameter takes the entire list as one argument with spaces between and the “$@” special parameter takes the entire list and separates it into separate arguments.
We can write the shell script as shown below to process an unknown number of commandline arguments with either the $* or $@ special parameters −
#!/bin/sh
for TOKEN in $*
do
echo $TOKEN
done
Here is a sample run for the above script −
$./test.sh Zara Ali 10 Years Old
Zara
Ali
10
Years
Old
Note − Here do…done is a kind of loop that will be covered in a subsequent tutorial.
Exit Status
The $? variable represents the exit status of the previous command.
Exit status is a numerical value returned by every command upon its completion. As a rule, most commands return an exit status of 0 if they were successful, and 1 if they were unsuccessful.
Some commands return additional exit statuses for particular reasons. For example, some commands differentiate between kinds of errors and will return various exit values depending on the specific type of failure.
Following is the example of successful command −
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
$echo $?
0
$