Shell Scripting Basics
1. What is a Shell?
A shell is an interface between the user and the operating system. It interprets user
commands and executes them.
Examples: sh, bash, zsh, ksh.
Bash is the most commonly used shell in Linux.
2. What is a Shell Script?
A shell script is a text file containing a series of shell commands.
Uses:
- Automation of tasks
- System administration
- File management
3. Creating a Shell Script
Steps:
1. Create file: vi [Link]
2. Add shebang: #!/bin/bash
3. Write commands
4. Give permission: chmod +x [Link]
5. Run: ./[Link]
4. Comments
# This is a comment
5. Variables
name="Rahmath"
echo $name
(No spaces around =)
6. User Input
read name
echo $name
7. Command Line Arguments
$0 - script name
$1, $2 - arguments
$# - number of arguments
$@ - all arguments
8. Conditional Statements
if [ condition ]
then
statements
fi
Operators:
-eq, -ne, -gt, -lt, -ge, -le
9. Loops
For Loop:
for i in 1 2 3
do
echo $i
done
While Loop:
i=1
while [ $i -le 5 ]
do
echo $i
i=$((i+1))
done
10. Arithmetic Operations
sum=$((a+b))
11. Case Statement
case $choice in
1) echo "One" ;;
2) echo "Two" ;;
*) echo "Invalid" ;;
esac
12. Functions
myfunc() {
echo "Hello"
}
myfunc
13. Exit Status
0 - Success
Non-zero - Failure
echo $?
14. Common Commands
ls, pwd, mkdir, rm, cp, mv, echo, read
Sample Script:
#!/bin/bash
read n
if [ $n -gt 0 ]
then
echo "Positive"
else
echo "Negative"
fi