Bash Tutorial
Bash (Bourne Again SHell) is a widely used Unix shell and command language. It is the default shell on most Linux distributions and macOS, and is popular for scripting, automation, and system administration.
How to Install Bash
Bash is pre-installed on most Linux and macOS systems. To check your version:
$ bash --version
To install or update Bash on Ubuntu:
$ sudo apt update
$ sudo apt install bash
How to Use Bash
1. Running Bash
Open a terminal and type commands directly, or write them in a script file (e.g., myscript.sh).
To run a script:
$ bash myscript.sh
$ chmod +x myscript.sh
$ ./myscript.sh
2. Basic Commands
ls— List files and directoriescd— Change directorypwd— Print working directoryecho— Print textcat— Display file contentscp— Copy filesmv— Move/rename filesrm— Remove files
Example:
ls -l
cd /home/user
pwd
echo "Hello, World!"
3. Variables
Assign a value to a variable (no spaces around =):
name="Alice"
echo $name
4. Conditionals
if [ "$name" = "Alice" ]; then
echo "Hello, Alice!"
else
echo "You are not Alice."
fi
5. Loops
For Loop:
for i in 1 2 3; do
echo $i
done
While Loop:
count=1
while [ $count -le 3 ]; do
echo $count
count=$((count + 1))
done
6. Functions
say_hello() {
echo "Hello, $1!"
}
say_hello "Bob"
7. Script Example
Create a file called greet.sh:
#!/bin/bash
name=$1
echo "Hello, $name!"
$ chmod +x greet.sh
$ ./greet.sh Alice
8. Cleaning Up
To clear the terminal screen:
$ clear
9. Advantages of Bash
- Ubiquity: Available on most Unix-like systems.
- Simplicity: Easy to learn and use for automation.
- Powerful scripting: Supports variables, conditionals, loops, and functions.
- Integration: Works well with other command-line tools.
10. Further Resources
Summary
Bash is a powerful and flexible shell for command-line users and script writers. Its simplicity and ubiquity make it a great tool for beginners and experts alike.