The Part#2 includes:
- Positional Parameters
- Shell Scripting Shift Through Parameters
- Shell Scripting Sourcing a file
- Accepting User input (STDIN)
- Shell Scripting Sourcing a config file
- Return codes / Exit statuses
- EXIT Command
- Functions
Positional Parameters:
- A bash shell script have parameters. These parameters start from $1 to $9.
- When we pass arguments into the command line interface, a positional parameter is assigned to these arguments through the shell.
- The first argument is assigned as $1, second argument is assigned as $2 and so on...
- If there are more than 9 arguments, then tenth or onwards arguments can't be assigned as $10 or $11.
- You have to either process or save the $1 parameter, then with the help of shift command drop parameter 1 and move all other arguments down by one. It will make $10 as $9, $9 as $8 and so on.
$1-$9 Represent positional parameters for arguments one to nine
${10}-${n} Represent positional parameters for arguments after nine
$0 Represent name of the script
$∗ Represent all the arguments as a single string
$@ Same as $∗, but differ when enclosed in (")
$# Represent total number of arguments
$$ PID of the script
$? Represent last return code
Example:
cat > positional.sh
#!/usr/bin/bash
echo "The script name: $0"
echo "The 1st argument: $1"
echo "The 2nd argument: $2"
echo "The pid of the script: $$"
echo "The total numbe rof arguments: $#"
echo "All the arguments: $*"
echo "The last return code: $?"
chmod +x positional.sh
./positional.sh
The script name: ./positional.sh
The 1st argument: 1
The 2nd argument: 4
The pid of the script: 4129020
The total numbe rof arguments: 2
All the arguments: 1 4
The last return code: 0
Shell Scripting Shift Through Parameters:
Shift command is a built-in command. Command takes number as argument. Arguments shift down by this number.
For example, if number is 5, then $5 become $1, $6 become $2 and so on.
The shift command is mostly used when arguments are unknown. Arguments are processed in a while loop with a condition of (( $# )). this condition holds true as long as arguments are not zero. Number of arguments are reduced each time as the shift command executes.
cat > shift.sh
#!/usr/bin/bash
if [ "$#" == "0" ]
then
echo pass at least one parameter
exit 1
fi
while (( $# ))
do
echo you gave me $1
shift
done
chmod +x shift.sh
./shift.sh
pass at least one parameter
./shift.sh 1 e
you gave me 1
you gave me e
Shell Scripting Sourcing a file:
A file is sourced in two ways.
- source <fileName>
- . ./<filename>
The difference between sourcing and executing a script is that, while executing a script it runs in a new shell whereas while sourcing a script, file will be read and executed in the same shell.
source ./variable.sh
jai viru
echo $var1
jai
. ./variable.sh
jai viru
echo $var2
viru
Accepting User input (STDIN):
The read command allows a user to provide the runtime input.
cat > read.sh
#!/usr/bin/bash
echo enter your name:
read name
echo "Welcome $name "
chmod +x read.sh
./read.sh
enter your name:
sri
Welcome sri
Syntax:
read -p "Prompt" variable
Example:
#!/usr/bin/bash
read -p "Enter your name" Name
echo " Hello $Name"
Output:
Enter your name
rabi
Hello rabi
Shell Scripting Sourcing a config file:
Many programs use external configuration files. Use of external configuration files prevents a user from making changes to a script. Config file is added with the help of source command.
If a script is shared in many users and every user need a different configuration file, then instead of changing the script each time simply include the config files.
We have two files, one is parent file (main.sh) and other is configuration file (config.sh). We have to source this configuration file into our parent file
Example 1:
Config.sh
#!/usr/bin/bash
user =java
id=201
Main.sh
#!/usr/bin/bash
source config.sh
echo “this is user $user with $id”
chmod +x main.sh
./main.sh
this is user abc with 101.
Note: We can also use ( . config.sh ) command instead of ( source config.sh ) .
Example 2:
cat > config.sh
#! /usr/bin/bash
user=abc
id=101
cat > main1.sh
#! /usr/bin/bash
. config.sh
echo "this is user $user"
chmod +x main1.sh
./main1.sh
Output:
this is user abc
Return codes / Exit statuses:
- Every command returns an exit codes, range from 0 to 255.
- 0=success and other than zero is a error condition.
- We can use this exit status as error checking purposes.
- $? returns the return code of the previously executed command.
Example:
#!/usr/bin/bash
HOST="google.com"
ping -c 1 $HOST
RETURN_CODE=$?
if [ $RETURN_CODE -eq "0" ]
then
echo "$HOST is reachable"
else
echo "$HOST is not reachable"
fi
chmod +x ret.sh
./ret.sh
PING google.com: (xxx.xxx.x.xx): 56 data bytes
64 bytes from xxx.xxx.x.xx: icmp_seq=0 ttl=111 time=42 ms
--- google.com ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 42/42/42 ms
google.com is reachable
&& and ||:
#!/usr/bin/bash
HOST="google.com"
#If 1st condition is true then it executes the second command.
ping -c 1 $HOST && echo " $HOST is reachable"
#If 1st condition is false then it executes the second command.
ping -c 1 $HOST || echo "$HOST is unreachbale"
The Semicolon:
It separates the commands with a semicolon to ensure they all get executed.
cp test.txt /test/bak/ ; cp tets.txt /test/
EXIT Command:
Using EXIT keyword we can explicitly define the return code. The default value is that of the last command executed. exit 0, exit 1, ....exit 255 etc.
Example:
#!/usr/bin/bash
HOST="google.com"
ping -c 1 $HOST
if [ $HOST -ne "0" ]
then
echo " $HOST unreachable"
exit 1
fi
exit 0
More examples:
ping -c 1 abc.com
PING abc.com: : 56 data bytes
64 bytes from : icmp_seq=0 ttl=238 time=42 ms
--- abc.com ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 42/42/42 ms
echo $?
0
ping -c 1 ttrert.com
0821-062 ping: host name ttrert.com NOT FOUND
echo $?
1
ping -c 1 amazon.com.1
0821-062 ping: host name amazon.com.1 NOT FOUND
echo $?
127
Functions:
With the help of functions, overall functionality of a function can be divided into smaller or logical parts, which can be called to perform their task. It helps us to check our program part by part. We can reuse the function where ever we want.
- Don't Repeat yourself(DRY)
- Write once, use many times
- easier to maintain and troubleshoot
Creating a function:
Syntax:
function functionName () {
Commands to be executed
}
or
functionName () {
Commands to be executed
}
You will call your function with their function name.
Example 1:
cat > function.sh
#!/usr/bin/bash
function helloWorld(){
echo "hello"
}
helloWorld
chmod +x function.sh
./function.sh
hello
Example 2:
cat > functest.sh
#!/usr/bin/bash
function hello(){
for NAME in $@
do
echo "Hello $NAME"
done
}
hello sri jinx pepa luis
chmod +x functest.sh
./functest.sh
Hello sri
Hello jinx
Hello pepa
Hello luis
Passing Parameters:
You can pass one or more parameters in a function. Parameters will be defined as $1, $2 and so on.
cat > funcparam.sh
#!/usr/bin/bash
function passParam(){
echo "param1= $1 and param2= $2"
}
#call function
passParam test 123
chmod +x funcparam.sh
./funcparam.sh
param1= test and param2= 123
Returning Values from Functions:
- If you execute an exit command from inside a function, its effect is not only to terminate execution of the function but also of the shell program that called the function.
Based on the situation you can return any value from your function using the return command whose syntax is as follows −
return code
cat > funcreturn.sh
#!/usr/bin/bash
Hello(){
echo "hello $1 $2"
return 10
}
Hello Sri Das
ret=$?
echo "return vaue is $ret"
chmod +x funcreturn.sh
./funcreturn.sh
hello Sri Das
return vaue is 10
Nested Functions:
One of the more interesting features of functions is that they can call themselves and also other functions. A function that calls itself is known as a recursive function.
Following example demonstrates nesting of two functions −
#!/bin/sh
# Calling one function from another
number_one () {
echo "This is the first function speaking..."
number_two
}
number_two () {
echo "This is now the second function speaking..."
}
# Calling function one.
number_one
To continue, go to the blog page part 3: bash-scripting-and-shell-programming_part3
No comments:
Post a Comment