[Day 7] 3. Back to Shell Scripting
Positional Parameters
Positional parameters are arguments passed to a script from the command line when you execute it. They allow you to pass data directly to the script.
Example Command:
./script27.sh 10 A sunbeam 3.142- ,
$1,$2, etc.: These refer to individual positional parameters.$3- =
$110 - =
$2A - =
$3sunbeam - =
$43.142
- : This is the name of the script itself (
$0)./script27.sh - : All positional parameters as a single string.
$* - : All positional parameters as individual strings.
$@ - : The process ID (PID) of the current shell.
$$ - : The number of positional parameters.
$#
Functions:
Functions allow you to organize and reuse code blocks inside your script. You can define a function using the
function()Example Syntax:
function my_function() { echo "This is a function." }- Calling the function: You simply call it by name.
- Arguments: Inside functions, arguments are accessed just like positional parameters, using ,
$1, etc.$2
Example:
my_function() { echo "First argument: $1" echo "Second argument: $2" } my_function "Hello" "World"This would output:
First argument: Hello Second argument: WorldArrays
In shell scripting, arrays allow you to store multiple values in a single variable. Arrays are indexed starting from 0.
Declaration:
declare -a arr arr=(5 3 6 8 2 1)-
Accessing array elements: Use
.${arr[index]}echo ${arr[0]} # prints first element (5) -
Printing all elements:
- : Prints all elements as a single string.
${arr[*]} - : Prints each element individually.
${arr[@]}
-
Number of elements: Use
to get the array length.${#arr[@]}
Example:
echo "Elements from index 2 onwards: ${arr[*]:2}" # prints from the 3rd element onwards (6 8 2 1)Strings
In shell scripting, strings are simple variables that hold text. You can compare and manipulate strings using operators.
Common Operators
- : True if both strings are equal.
= - : True if both strings are not equal.
!= - : True if the string is not empty.
-n - : True if the string is empty.
-z
String Concatenation
You can concatenate two strings as follows:
str1="Ojas" str2="Dudhabaware" str3=$str1$str2 echo "Concatenated String: $str3" # Output: OjasDudhabawaretest
Command
testThe test
0Example of Checking Exit Status:
test -f myfile.txt echo $? # Outputs 0 if the file exists, 1 otherwiseUsing testif
if test -f "myfile.txt"; then echo "File exists" else echo "File does not exist" fiBy using the
echo $?0Read Next
[Day 1] 1. Operating System
!1. OS.png ### **Operating System (OS)** An Operating System is a crucial software that enables hardware to function by acting as an interface b...
[Day 1] 2. Functions of Operating System
### **Functions of an Operating System (OS)** The Operating System performs several critical functions that ensure the smooth operation of a comput...