Bash scripting is a powerful way to automate tasks and manage systems in Unix/Linux environments
Creating your first script:
#!/bin/bash
echo "Hello, World!"Making scripts executable:
chmod +x script.shRunning scripts: ./script.sh
1. Basic Commands & File System Navigation:
pwd: Print working directory.ls: List directory contents.cd: Change directory.mkdir: Create directory.cp: Copy files/directories.mv: Move/rename files/directories.- mv old_filename new_filename
- mv report.txt final_report.txt
- mv /home/user/oldname.txt /home/user/newname.txt
rm,rmdir: Remove files/directories.- rm -r folder_name
- rmdir directory_name
- rm -rf folder_name
-r: recursive (deletes subdirectories and files inside)-f:force (ignores nonexistent files and never asks for confirmation)
cat,less,more: View file contents.
2. Variables and Data Types
name="Amrit"
echo "Hello, $name"
_arg_install= # Unset/empty variable
_arg_wsl="off"
_arg_publish=() # Declares an empty array_arg_publish=()
This defines an empty array, which can be later filled like:
_arg_publish+=("pkg1")
_arg_publish+=("pkg2")
# this will append the element
_arg_publish=("pkg1")
# will will override the array
# you can write string directly as
_arg_publish=(pkg3)Access:
echo "${_arg_publish[@]}" # All elements
echo "${_arg_publish[0]}" # First element
Special Variables: $0 (script name), $1, $2 (positional parameters), $# (number of arguments), $? (exit status of last command).
Read user input:
read -p "Enter your name: " nameRedirection:
>: Redirect standard output to a file (overwrites).>>: Redirect standard output to a file (appends).<: Redirect standard input from a file.2>: Redirect standard error.&>: Redirect both standard output and standard error.
3. Conditional Statements:
if statements
if [ "$name" == "Amrit" ]; then
echo "Welcome!"
else
echo "Access denied"
fi
Operators: -eq (equal), -ne (not equal), -gt (greater than), -lt (less than), -f (file exists), -d (directory exists).
case statement
case $variable in
pattern1)
# commands
;;
pattern2)
# commands
;;
*)
# default commands
;;
esacLoop
for,while,until
for loop.
for item in list; do
# commands
donewhile loop:
while [ condition ]; do
# commands
donefor i in {1..5}
do
echo "Count: $i"
done5. Arithmetic Operations
a=5
b=3
let sum=a+b
echo $sumOr use $(( )):
sum=$((a + b))
6. Functions
Definition.
function_name() {
# commands
}Calling:
function_name
greet() {
echo "Hello, $1!"
}
greet "Amrit"7. Handling Files
- Reading and writing files
- Using loops to read line-by-line
while read line; do
echo "$line"
done < file.txt8. Script Arguments and Flags
When you run a Bash script, you can pass values (arguments) to it from the command line. These values are accessible inside the script using special variables like $1, $2, $@, etc.
echo "Script name: $0"
echo "First argument: $1"
echo "All arguments: $@"| Variable | Description |
|---|---|
$0 | Name of the script |
$1 | First argument |
$2 | Second argument |
$@ | All arguments (as separate strings) |
$* | All arguments (as one string) |
$# | Number of arguments |
Additional commands:
1. bin_dir=$(dirname "$0")
dirname command returns the directory portion of a path.
abc=$(dirname /home/amrit/scripts/myscript.sh)
# Output: /home/amrit/scripts2.app_name=$(basename $PWD)
This is a command-line utility that strips the directory path and returns just the last part (the folder or file name).
basename /home/amrit/projects/myapp
# Output: myapp
Flags / Options (Advanced Argument Parsing)
Flags are like --help, -v, -f filename, etc., that control how your script behaves.
There are two common tools in Bash for parsing flags:
getopts(for short options:-f)getopt(for long options:--file)
Using getopts (for short options like -f)
#!/bin/bash
while getopts "f:v" opt; do
case $opt in
f)
echo "File: $OPTARG"
;;
v)
echo "Verbose mode ON"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
donegetopts Explained:
"f:v"means:fexpects a value (-f filename)vis a flag (no value)
OPTARGholds the argument passed to the option.
Run script:
./script.sh -f myfile.txt -vOutput:
File: myfile.txt
Verbose mode ONIf your script has flags followed by positional arguments:
#!/bin/bash
while getopts "f:" opt; do
case $opt in
f) FILE=$OPTARG ;;
esac
done
shift $((OPTIND -1)) # Remove parsed options from $@
echo "Remaining argument: $1"
9. Useful Commands in Scripts
grep,awk,sed,cut,xargs,find,curl,wget
find . -name "*.log" -delete10. Advanced Topics
- Permissions:
chmod,chown - Cron jobs (scheduling scripts)
- Trap and signals
- Arrays in Bash
- Here documents (
<<EOF) - Sourcing other scripts (
sourceor.) Crontab: Scheduling tasks.
Debugging:
set -x,set -e.
other commands:
ls -al ~/.ssh1. ls
- This is the list command in Linux/Unix.
- It shows the contents of a directory (files and folders).
2. -a
- This option stands for all.
- By default,
lsdoes not show hidden files (files starting with.). -aensures you see all files, including hidden ones.- Example:
.bashrc,.ssh,.profileare hidden files.
- Example:
3. -l
- This option stands for long listing format.
- It shows detailed info about each file, like:
- File type (
dfor directory,-for regular file,lfor link) - Permissions (e.g.,
rw-r--r--) - Number of links
- Owner
- Group
- File size
- Last modification date
- File name
- File type (
4. ~/.ssh
~is shorthand for your home directory (/home/username)..sshis a hidden folder in your home directory where SSH keys and configurations are stored.- Files you might see:
id_rsa? your private SSH keyid_rsa.pub? your public SSH keyauthorized_keys? list of public keys allowed to log inconfig? optional SSH client configuration
- Files you might see:
