Bash (Bourne Again SHell) is a widely used command language interpreter for the GNU operating system. It offers scripting capabilities, allowing for task automation, program execution, and more. Bash is a powerful tool for managing servers, automating tasks, and developing in a Linux environment.
Basic Bash Commands
Running Scripts
Execute a script:
Make a script executable and run it:
1
2
| chmod +x ./script.sh
./script.sh
|
File System Operations
Change directory:
Return to the home directory:
Move back one directory:
Copy files:
1
| cp /path/to/file /path/to/destination
|
Move files:
1
| mv /path/to/file /path/to/destination
|
List files in the current directory:
List all files, including hidden ones:
List files in a specific directory:
Create a new file:
Create a new directory:
Delete files:
Delete a directory and its contents:
Writing to Files
Append text to a file:
1
| echo "Hello, World!" >> file.txt
|
Overwrite text in a file:
1
| echo "Hello, World!" > file.txt
|
Bash Variables
Defining variables:
1
2
3
| name="John"
age=30
is_admin=true
|
Accessing variables:
String Manipulation
Convert to uppercase:
1
2
| msg="hello"
echo ${msg^^}
|
Convert to lowercase:
1
2
| msg="HELLO"
echo ${msg,,}
|
Replace text in a string:
1
2
| msg="hello world"
echo ${msg/world/universe}
|
Arrays
Defining an array:
1
| my_array=(apple banana cherry)
|
Accessing array elements:
1
| echo ${my_array[0]} # Outputs 'apple'
|
Adding elements to an array:
Associative Arrays (Dictionaries)
Defining an associative array:
1
2
3
| declare -A user
user[name]="John"
user[age]=30
|
Accessing associative array elements:
Passing Arguments to Scripts
1
| ./script.sh arg1 arg2 arg3
|
Inside script.sh
:
1
2
| echo $1 # First argument
echo $2 # Second argument
|
System Variables
Commonly used system variables:
1
2
3
4
| echo $USER # Current username
echo $BASH_VERSION # Bash version
echo $PWD # Current directory
echo $HOME # Home directory
|
Reading user input:
1
2
3
| echo "Enter your name:"
read name
echo "Hello, $name"
|
Silent input (e.g., for passwords):
Flow Control
If Statement
1
2
3
4
5
6
7
| if [ condition ]; then
# commands
elif [ other_condition ]; then
# other commands
else
# else commands
fi
|
Loops
While Loop
1
2
3
| while [ condition ]; do
# commands
done
|
For Loop
Loop over a range of numbers:
1
2
3
| for i in {1..10}; do
echo $i
done
|
Loop over a list:
1
2
3
| for i in apple banana cherry; do
echo $i
done
|
Functions
Defining a function:
1
2
3
| function greet {
echo "Hello, $1"
}
|
Calling a function with arguments:
Advanced Concepts
Process Control
Background a process:
Kill a process:
Text Processing
Using grep
to search inside files:
1
| grep "pattern" file.txt
|
Using awk
for pattern scanning and processing:
1
| awk '/pattern/ { print $0 }' file.txt
|
Using sed
for stream editing:
1
2
3
| sed 's/old/new/g' file
.txt
|
Networking
Download files with wget
:
Transfer files with scp
:
1
| scp file.txt user@remote:/path
|