Okay, so in this blog post, we'll summarise all we've learned about Linux over the previous six or seven days. We'll write a straightforward Bash Script.
The script will ask the user for their name, and it will create a folder called LoginDetails
and put their entry with the date and time to a file called login.txt
.
BASH Script 📜
But first, what exactly is Bash? When running Linux and UNIX commands, Bash is actually what you see as a terminal window. Bash Shell is the usual name for it.
Bash, as it is known technically, is a text-based command line interpreter that often runs in a text window where users can interpret commands to perform various activities.
Ok now let's start creating the script:
Step 1: Create a new file UserLogins.sh
Create a new file with the nano UserLogins.sh
command. If you try to execute that file, a "Permission denied" error will appear. This is due to the fact that you don't have a permission to execute that file. Don't worry; we learnt how to handle that in a prior blog. To grant execute permission to your file, use chmod +x UserLogins.sh
.
Step 2: Edit that file with your logic.
Okay, the file has been generated; now we need to add our script to it. Keep in mind that the first line of any Bash script will begin with either #!/bin/bash
or #!/usr/bin/env bash
. It is actually the location of our Bash binary file. Using which bash
, you can also verify that.
#!/usr/bin/env bash
echo "Welcome $(whoami)!"
DIRNAME="LoginDetails"
if [ -d "$DIRNAME" ]
then
echo "$DIRNAME exists"
else
mkdir LoginDetails
fi
cd LoginDetails
echo "$(whoami) logged in at $(date)" >> login.txt
We will first greet our user, but how will we know who is now using the system? There is only one command that returns the current user, whoami
.
After that, we will assign the directory name to a variable called DIRNAME
.
What if the LoginDetails
folder has already been created? We must set up certain conditions for that at this place. Print LoginDetails exists
if DIRNAME
already exists otherwise, build it using mkdir LoginDetails.
A new file called login.txt
will now be created in the LoginDetails
folder. It will request the current whoami and date values from the system and append them to the file.
View the file content that we had in mind for this output. Our initial Bash script performed very well. By using Cron Jobs,
you may take this a step further by setting your script to run at a certain time. Schedule your script in a new cronjob.
Resources & Ending Note 👋
All right, that's it for today. Today, we successfully executed the first Bash script we had written. This was just a basic script but there are more advance level scripts available, we will see that in the following blog.