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:
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:
This command gives your script execution permissions. Now, you can run the script by typing:
Shebang (#!) and Specifying the Shell π
Adding a shebang at the top of your script specifies which shell should interpret the script commands. For example:
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:
This script will produce output like this:
Adding Improvements: Formatting Output with echo
π¬
To make the output more user-friendly, let’s enhance it with echo
and special characters:
Expected Output:
This script uses:
-e
inecho
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:
This produces:
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
Post a Comment