Skip to main content

Getting Started with Shell Scripting in Unix/Linux πŸ§πŸ’»


    Creating and running scripts in Unix/Linux can simplify repetitive tasks, automate processes, and make your workflow more efficient. Whether you're checking logged-in users, displaying the date, or showcasing your current working directory, shell scripting can help you do it all with just a few lines of code. Let’s walk through the basics of creating and running a simple shell script, exploring built-in commands, and enhancing our script with special characters in echo statements.

Writing Your First Script ✍️

Imagine you want to create a script that shows the current date and all users currently logged in. To start, open your favorite text editor (like nano or vim) and type the following commands:

date
echo "Users currently logged in:"
who

After typing, save this file with a name like check_users.sh. This script uses:

  • date to display the current date.
  • echo to print a message.
  • who to list all currently logged-in users.

Making the Script Executable πŸš€

Before you can run your script, you need to mark it as executable. To do this, use the chmod command:

chmod +x check_users.sh

This command gives your script execution permissions. Now, you can run the script by typing:

./check_users.sh

Shebang (#!) and Specifying the Shell πŸ“œ

Adding a shebang at the top of your script specifies which shell should interpret the script commands. For example:

#!/bin/bash

This line tells the system to use bash as the interpreter. Other popular shells include:

  • #!/bin/ksh for Korn shell
  • #!/bin/sh for Bourne shell

Anything following the # character in the code is treated as a comment, allowing you to add notes or explanations directly into your script for clarity.

Using Built-in Commands πŸ› ️

Unix/Linux shells like Bourne, Korn, and Bourne Again (Bash) come with built-in commands. Here are a few commonly used ones that help control the flow of scripts:

  • exit: Ends the script or command session.
  • if, for, while, until: Control structures for condition-based and looped operations.
  • let: Performs arithmetic operations.
  • read: Reads input from the user.
  • test: Evaluates conditions (such as checking if a file exists).

These built-ins allow for more advanced functionality and customization in scripts.

Enhanced Script: Displaying Date, Users, and Directory πŸ“…πŸ‘₯πŸ“‚

Here’s an example script that displays the current date, the number of logged-in users, and your current working directory path:

#!/bin/bash
#
# Displays the current date and time, number of users logged on,
# and the full path of the current working directory.
date # Display the current date
who | wc -l # Display the number of users logged in
pwd # Display the current working directory

This script will produce output like this:

Wednesday February 1 14:54:35 GMT 2023
32
/home/username/current_directory

Adding Improvements: Formatting Output with echo πŸ’¬

To make the output more user-friendly, let’s enhance it with echo and special characters:

#!/bin/bash
#
# Displays the current date and time, the number of users on the system,
# and the full path of the current working directory.
echo # Skips a line for readability
echo -e "Date and time: \c" # `\c` keeps output on the same line
date
echo -e "Number of users on the system: \c"
who | wc -l
echo -e "Your current working directory: \c"
pwd
echo # Adds an extra line at the end

Expected Output:

Date and time: Wednesday February 1 15:14:14 GMT 2023
Number of users on the system: 18
Your current directory: /home/username/current_directory

This script uses:

  • -e in echo to enable interpretation of backslash escapes.
  • \c to keep output on the same line.
  • Empty echo statements to add blank lines for readability.

Special Characters in echo 🎩

The echo command supports escape characters to control output formatting. Here are a few helpful ones:

  • \b: Backspace
  • \c: Keeps output on the same line
  • \n: Newline
  • \r: Carriage return (moves to the start of the line)
  • \t: Tab
  • \0n: ASCII code in octal form for special characters

Example:

echo -e "Welcome to Unix/Linux Scripting!\nLet’s automate tasks!"

This produces:

Welcome to Unix/Linux Scripting!
Let’s automate tasks!

Wrapping Up 🌟

With these scripting basics, you’re ready to start creating scripts that save time, automate processes, and simplify daily tasks. Start small by trying out different commands and adding them to scripts, then experiment with built-ins, command chaining, and custom formatting to level up your scripts! Happy scripting! πŸŽ‰ 

Comments

Popular posts from this blog

Unraveling the Apache Hadoop Ecosystem: The Ultimate Guide to Big Data Processing πŸŒπŸ’ΎπŸš€

In the era of big data, organizations are constantly seeking efficient ways to manage, process, and analyze large volumes of structured and unstructured data. Enter Apache Hadoop , an open-source framework that provides scalable, reliable, and distributed computing solutions. With its rich ecosystem of tools, Hadoop has become a cornerstone for big data projects. Let’s explore the various components and layers of the Hadoop ecosystem and how they work together to deliver insights. Data Processing Layer πŸ› ️πŸ” The heart of Hadoop lies in its data processing capabilities, powered by several essential tools: Apache Pig 🐷 : Allows Hadoop users to write complex MapReduce transformations using a scripting language called Pig Latin , which translates to MapReduce and executes efficiently on large datasets. Apache Hive 🐝 : Provides a SQL-like query language called HiveQL for summarizing, querying, and analyzing data stored in Hadoop’s HDFS or compatible systems like Amazon S3. It makes inter...

Essential Unix Terminal Commands: A Handy Guide for Beginners πŸ–₯️

  If you're working in a Unix-like environment (like Linux or macOS), mastering the command line is key to unlocking the full potential of your system. The terminal allows you to perform powerful operations by executing commands directly. In this guide, we’ll cover some of the most commonly used Unix terminal commands to help you get started! 1. alias – Create Shortcuts for Commands πŸ”— The alias command allows you to create shortcuts for longer commands, making them easier to type and remember. alias ll= 'ls -la' Here, ll is now an alias for ls -la . You can create any alias you like to save time. 2. at – Schedule a Command for Later ⏰ The at command lets you schedule a command to run at a specified time. at 5:00 PM Enter the command you want to run at 5:00 PM, press Ctrl+D to schedule it. 3. cal – Display a Calendar πŸ“… The cal command displays a calendar for the current month. You can specify a year to view its entire calendar. cal 2024 4. cat – Concatena...

Real-Time Monitoring with tail -f: A Guide to Watching Logs Like a Pro πŸš€πŸ“œ

  Whether you’re troubleshooting a server or just monitoring your app’s health, there’s one command that stands out for real-time log monitoring: tail -f . This simple command can be a game-changer for anyone managing logs in a Linux or Unix environment. Let’s explore how you can make the most of tail -f for real-time log watching. What is tail -f ? 🧐 The tail command is designed to display the last few lines of a text file. By adding the -f option, you tell tail to keep the file open and display new lines as they’re added. This is incredibly useful for tracking real-time log files that are actively being written to, such as server or application logs. In essence: tail -f /path/to/log/file.log The -f flag lets you “follow” the log as new entries are added, giving you a live, scrolling view of what’s happening inside that file. Why Use tail -f ? 🌟 Imagine you’ve just deployed a new version of your application, and you want to watch for errors. Rather than constantly opening...