Shell Scripting (Part-2)

I'm Yasheela, an undergraduate with a deep interest in DevOps, and cloud technologies. Currently working on exciting projects on all things DevOps. I’m passionate about simplifying complex concepts and sharing practical insights. Through my Hashnode blog, I document my learning journey, from building scalable applications to mastering cloud services, with the goal of empowering others to grow their tech skills. Let's Learn Together !!
Shell scripting and command-line usage are essential skills for a Linux power user.
In this part, I’ll cover the most important shell commands and scripting essentials from scratch, assuming you're aiming to become proficient.
Basic Linux Commands
1. File Management
ls: Lists directory contents.ls # List files in the current directory ls -l # List files with detailed information ls -a # Include hidden files in the listing ls -lh # Human-readable sizescd: Change directory.cd /path/to/directory # Navigate to a directory cd .. # Move to the parent directory cd ~ # Go to home directorymkdir: Create a new directory.mkdir myfolder # Create a directory named 'myfolder'cp: Copy files.cp source.txt destination.txt # Copy a file cp -r /source/ /destination/ # Copy directories recursivelymv: Move or rename files.mv file1.txt file2.txt # Rename file1 to file2 mv /source/ /destination/ # Move filesrm: Remove files or directories.rm file.txt # Delete a file rm -r directory # Remove directory and its contents rm -f file.txt # Force delete (use with caution)
File Viewing and Manipulation
cat: Display the content of a file.cat file.txt # Show file contentsmoreandless: View large files one page at a time.less file.txt # View file contents (scroll with arrows)headandtail: View the start or end of a file.head -n 5 file.txt # Show the first 5 lines tail -n 5 file.txt # Show the last 5 linesgrep: Search for patterns in files.grep 'pattern' file.txt # Search for 'pattern' in file grep -r 'pattern' /path/ # Recursive search in directoryfind: Search for files in a directory hierarchy.find /path/ -name '*.txt' # Find all .txt files under /path/touch: Create an empty file or update a file’s timestamp.touch newfile.txt # Create a new file
File Permissions
chmod: Change file permissions.chmod 755 file.sh # Give the owner full permissions, others read-executechown: Change file ownership.chown user:group file.txt # Change the owner and group
File Permissions Structure:
r: Read
w: Write
x: Execute
Permissions are defined using numeric codes (owner, group, others):
7: Read, write, execute6: Read, write5: Read, execute4: Read only
Process Management
ps: Show running processes.ps aux # Display all running processes with detailed infotop: Display real-time processes and system resource usage.top # View real-time system processes and memory usagekill: Terminate a process.kill PID # Kill process by PID (Process ID) kill -9 PID # Force kill a process (use carefully)&: Run a command in the background.command & # Run 'command' in the backgroundjobs: List background jobs.jobs # List all background jobs
Networking Commands
ifconfig: Display network interfaces.ifconfig # Show network interface info (IP address, etc.)ping: Check network connectivity.ping google.com # Test network connection to a hostnetstat: Display network connections and listening ports.netstat -tuln # Show listening portsscp: Securely copy files between hosts.scp file.txt user@remote:/path/ # Copy file to a remote hostssh: Securely connect to a remote host.ssh user@remote_ip_address # Connect to remote machine over SSH
System Monitoring and Management
df: Check disk space usage.df -h # Show disk space usage in human-readable formatdu: Check directory size.du -sh /directory/ # Show the size of a directoryuptime: Check system uptime.uptime # Show how long the system has been runningfree: Display memory usage.free -h # Show system memory usage (RAM)
Text Processing Commands
awk: Pattern scanning and text processing.awk '{print $1}' file.txt # Print the first column of a filesed: Stream editor for text manipulation.sed 's/old/new/g' file.txt # Replace 'old' with 'new' in filecut: Remove sections from each line of files.cut -d':' -f1 /etc/passwd # Display the first field (username) in /etc/passwd
Shell Scripting Basics
A shell script is simply a series of commands stored in a file.
Example 1: Simple Shell Script
- Create a script file:
touch myscript.sh
- Open the file in a text editor (e.g.,
nanomyscript.sh) and add the following code:
#!/bin/bash
# This is a comment
echo "Hello, World!"
- Make the script executable and run it:
chmod +x myscript.sh
./myscript.sh
Example 2: Using Variables and Arguments
#!/bin/bash
name=$1 # First argument to the script
echo "Hello, $name"
Run it:
./myscript.sh Alice
Output:
Hello, Alice
Example 3: Control Structures (If-Else, Loops)
If-Else:
#!/bin/bash
if [ $1 -gt 10 ]; then
echo "Number is greater than 10"
else
echo "Number is less than or equal to 10"
fi
For Loop:
#!/bin/bash
for i in {1..5}; do
echo "Welcome $i times"
done
While Loop:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Iteration $count"
((count++))
done
Redirecting Input and Output
>: Redirect standard output to a file (overwrite).echo "Hello" > file.txt # Overwrites file.txt with "Hello">>: Append standard output to a file.echo "Hello" >> file.txt # Appends "Hello" to file.txt<: Redirect input from a file.wc -l < file.txt # Count lines in file.txtPiping (
|): Send the output of one command as input to another.ls -l | grep ".txt" # List .txt files in the current directory
Permissions and User Management
adduser: Add a new user.sudo adduser newuser # Create a new user with home directorypasswd: Change a user’s password.sudo passwd newuser # Set password for the new useruserdel: Delete a user account.sudo userdel newuserusermod: Modify a user account.sudo usermod -aG groupname username # Add a user to a groupgroups: Show the groups a user belongs to.groups username # List groups for the specified userwho: Display who is currently logged in.who # Show logged-in userslast: Show the last logged-in users.last # Display login history
System Information Commands
uname: Display system information.uname -a # Show all system informationhostname: Display or set the system’s hostname.hostname # Show the hostnamelscpu: Display CPU architecture information.lscpu # Show CPU detailslsblk: List block devices.lsblk # Display information about all block devicesdf -i: Check inode usage.df -i # Show inode usage for filesystems
Package Management
Depending on your Linux distribution, package management commands can vary. Here are commands for Debian/Ubuntu and Red Hat/CentOS:
Debian/Ubuntu: apt
Update package index:
sudo apt update # Update package informationInstall a package:
sudo apt install package_name # Install specified packageRemove a package:
sudo apt remove package_name # Remove specified packageUpgrade installed packages:
sudo apt upgrade # Upgrade all installed packages
Red Hat/CentOS: yum or dnf
Update package index:
sudo yum check-update # Check for package updatesInstall a package:
sudo yum install package_name # Install specified packageRemove a package:
sudo yum remove package_name # Remove specified packageUpgrade installed packages:
sudo yum update # Upgrade all installed packages
Cron Jobs
Cron jobs allow you to schedule tasks to run automatically at specified intervals.
Edit crontab:
crontab -e # Edit the current user's cron jobs
Crontab Format:
* * * * * command_to_run
- - - - -
| | | | |
| | | | +---- Day of the week (0-6, 0 is Sunday)
| | | +------ Month (1-12)
| | +-------- Day of the month (1-31)
| +---------- Hour (0-23)
+------------ Minute (0-59)
Example Cron Job:
Run a script every day at 5 AM:
0 5 * * * /path/to/script.sh
Advanced Shell Scripting Concepts
Functions in Shell Scripts
Functions help to organize scripts into reusable blocks of code.
#!/bin/bash
function greet {
echo "Hello, $1!" # Function that greets the user
}
greet "Alice" # Call the function with 'Alice' as an argument
Arrays
Bash supports one-dimensional arrays.
#!/bin/bash
my_array=(apple banana cherry) # Declare an array
echo ${my_array[0]} # Access the first element
echo ${my_array[@]} # Access all elements
Error Handling
To handle errors in scripts, you can check the exit status of commands.
#!/bin/bash
cp file.txt /destination/
if [ $? -ne 0 ]; then # Check if the previous command failed
echo "Copy failed!"
else
echo "Copy successful!"
fi
Debugging Scripts
Use the -x option to enable debugging.
bash -x myscript.sh # Run the script in debug mode
Environment Variables
Environment variables store system-wide values that affect the behavior of processes.
Common Environment Variables
$HOME: Home directory of the current user.$USER: The name of the current user.$PATH: A list of directories to search for executable files.
Setting Environment Variables
export MY_VAR="Hello World" # Set a new environment variable
echo $MY_VAR # Display the variable
Redirection and Pipes
Redirecting Standard Error:
command 2> error.log # Redirect error messages to a fileRedirecting both Output and Error:
command &> output.log # Redirect both stdout and stderrUsing Pipes:
command1 | command2 # Pipe output of command1 to command2
Conclusion
Mastering these essential commands and shell scripting concepts will greatly enhance your productivity as a Linux user. Start practicing these commands in a Linux environment to build your proficiency. If you have any specific questions or need further clarification on any topic, feel free to ask!
Happy Linux’ing :)


