1. Shell Special Variables
2. eval command
3. colon command
4. sleep command
5. trap command
1. Shell Special Variables
In the previous chapters we have used special operators like “$0” “$1” “$?”, which did not make much sense then. In this section we shall understand in detail about these variables.
$0 It holds the name of the script currently executing
$n “n” is a place holder for integer variable. If the input has 4 argument, then all the 4 argument can be accessed by: $1 for first argument, $2 for second argument, $3 for argument etc.
$# It outputs the number of arguments sent to the script.
$? Gives the exit status of the last command executed.
$$ Returns the process number of the current shell
$! Process number of the last background running process.
There are 2 other special variables that are tricky to understand. They are:
$*
$@
Their behaviour changes when they are used with and without quotes.
1. With quotes:
“$*”
“$@”
and call it with:
./myScript.sh "a a" "b b" "c c"
it’s equivalent to:
“$*” will return “a a b b c c”
“$@” will return “a a” “b b” “c c”
2. When used without quotes, they’re the same:
$*
$@
would be equivalent to:
$* “a” “a” “b” “b” “c” “c”
$@ “a” “a” “b” “b” “c” “c”
Example:
#!/bin/bash
echo "The script name is $0"
echo "The first argument is $1"
echo "The second argument is $2"
echo "The third argument is $3"
echo "Total number of variables entered $#"
echo "All the entered variables $*"
echo "All the entered variables $@"
echo "The process number of the current shell is $$"
Output:
sh 20_example.sh 123 345
The script name is 20_example.sh
The first argument is 123
The second argument is 345
The third argument is
Total number of variables entered 2
All the entered variables 123 345
All the entered variables 123 345
The process number of the current shell is 10774
2. eval command
eval command is used to execute arguments as a shell command.
For example:
a=5
b='$a'
eval echo $b
Output
5
In the above example, we expect the output to be “5” but instead it returns “$a”. Because the shell will take it as a string variable. To get the correct value use “eval” command.
a=5
b='$a'
echo $b
Output
$a
3. colon command
In earlier times, there was no true or false value in shell script. Hence “:” was used as true and “0” was used as false.
4. sleep command
sleep command is used to pause the execution for the given number of seconds.
5. trap command
trap command is used to catch a signal during the script execution.
Example:
Create a file 21_trap.sh
#!/bin/bash
#set a trap for exit with 0, when the script will exit with 0, this will be executed
trap 'echo "Exit 0 signal detected..."' 0
echo "Sample text"
exit 0
Output:
Sample text
Exit 0 signal detected...