# 🐧💻 Automate Tasks on Linux with Scripting - A Comprehensive Guide 🚀📝

1. ***You have to do the same using Shell Script i.e using either Loops or command with start day and end day variables using arguments -***
    

So Write a bash script [**create**](http://createdirectories.sh/) [**directories.sh**](http://directories.sh) that when the script is executed with three given arguments (one is the directory name and the second is the start number of directories and the third is the end number of directories ) it creates a specified number of directories with a dynamic directory name:

### *Answer :*

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Let's understand what are loops in Linux.</strong></div>
</div>

In Linux, a loop is a programming construct that allows you to repeat a block of code a certain number of times. There are three main types of loops in Linux:

1. **For loop:** The for loop is used to iterate over a list of items. The syntax for a for loop is as follows:
    

**COPY**

```plaintext
for var in item1 item2 item3 ...
do
   commands
done
```

The var variable will be assigned the value of each item in the list, one by one. The commands block of code will then be executed for each value of var.

1. **While loop:** The while loop is used to repeat a block of code as long as a certain condition is met. The syntax for a while loop is as follows:
    

**COPY**

```plaintext
while condition
do
   commands
done
```

The condition expression will be evaluated before each iteration of the loop. If the condition is true, the commands block of code will be executed. If the condition is false, the loop will terminate.

Loops are a powerful tool that can be used to automate repetitive tasks. They can also be used to control the flow of your code. If you are new to Linux, I recommend that you learn about loops so that you can use them to make your scripts more efficient.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong><em>Let's create day 1 to 90 directories using a loop for our #90daysofdevops</em></strong></div>
</div>

I m using aws ec2 to run the UBUNTU server for this task :

create directory: create\_[**directories.sh**](http://directories.sh/)

**COPY**

```plaintext
ubuntu@ip-172-31-91-254:~$ vim create_directories.sh
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">write a script for creating 1 to 90 directories</div>
</div>

**COPY**

```plaintext
#!/bin/bash

# Check if three arguments are given
if [ "$#" -ne 3 ]; then
  echo "Usage: ./create_directories.sh <start-number> <end-number>"
  exit 1
fi

# Get the start and end numbers
start_number=$1
end_number=$2
day=$3
# Start at the start number
i=$start_number

# Loop until i is the end number
while [ $i -le $end_number ]; do

  # Create the directory
  mkdir "$day$i"

  # Increment i
  i=$((i + 1))
done

# Print a success message
echo "Directories $start_number to $end_number created!"
```

change permission to execute script file

**COPY**

```plaintext
ubuntu@ip-172-31-91-254:~$ chmod 777 create_directories.sh
```

execute script :

**COPY**

```plaintext

ubuntu@ip-172-31-91-254:~$ ./create_directories.sh 1 90 DAY
Directories 1 to 90 created!
```

check if our script created 1 to 90 folders :

**COPY**

```plaintext
DAY1   DAY15  DAY20  DAY26  DAY31  DAY37  DAY42  DAY48  DAY53  DAY59  DAY64  DAY7   DAY75  DAY80  DAY86 
DAY10  DAY16  DAY21  DAY27  DAY32  DAY38  DAY43  DAY49  DAY54  DAY6   DAY65  DAY70  DAY76  DAY81  DAY87 
DAY11  DAY17  DAY22  DAY28  DAY33  DAY39  DAY44  DAY5   DAY55  DAY60  DAY66  DAY71  DAY77  DAY82  DAY88  
DAY12  DAY18  DAY23  DAY29  DAY34  DAY4   DAY45  DAY50  DAY56  DAY61  DAY67  DAY72  DAY78  DAY83  DAY89  create_directories.sh
DAY13  DAY19  DAY24  DAY3   DAY35  DAY40  DAY46  DAY51  DAY57  DAY62  DAY68  DAY73  DAY79  DAY84  DAY9  
DAY14  DAY2   DAY25  DAY30  DAY36  DAY41  DAY47  DAY52  DAY58  DAY63  DAY69  DAY74  DAY8   DAY85  DAY90
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Explanation of what is happening in script.</div>
</div>

To run this code, you need to pass the start and end numbers as arguments. For example, to create directories 1 to 90 with the directory name my\_directories, you would run the following command:

*./create\_*[***directories.sh***](http://directories.sh/) *1 90 DAy*  
This will create directories 1 to 90 with the directory name my\_directories in the current directory.

Here is an explanation of the different parts of the code:

* The first line specifies that the script is a bash script.
    
* The second line checks if three arguments are given. If not, the script will print a usage message and exit.
    
* The third line gets the start and end numbers from the arguments.
    
* The fourth line starts the loop at the start number.
    
* The fifth line is the while loop condition. The loop will continue to run as long as the value of i is less than or equal to the end number.
    
* The sixth line creates the directory. The directory name is the current value of i concatenated with the directory name specified as the third argument.
    
* The seventh line increments i. This will ensure that the next iteration of the loop will create the next directory.
    
* The eighth line prints a success message. This message will be printed when the loop has finished running.
    

---

***Task 2. Create a Script to back up all your work done till now.***

**Answer :**

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Create <a target="_blank" rel="noopener noreferrer nofollow" href="http://backup.sh" style="pointer-events: none"><strong>backup.sh</strong></a> script</div>
</div>

**COPY**

```plaintext
#!/bin/bash
# Get the current working directory
current_directory=$(pwd)

# Get the date and time
date=$(date +"%Y-%m-%d_%H-%M-%S")

# Create the backup directory
backup_directory="$current_directory/backups/$date"
mkdir -p "$backup_directory"

# Recursively backup all files in the current directory
find "$current_directory" -type f -exec cp -r {} "$backup_directory" \;

# Print a success message
echo "Backup complete!"
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">change permission and execute script file .</div>
</div>

**COPY**

```plaintext
ubuntu@ip-172-31-91-254:~$ chmod 777 backup.sh 
ubuntu@ip-172-31-91-254:~$ ./backup.sh
```

Check if backup is going on :

**COPY**

```plaintext
cp: '/home/ubuntu/backups/2023-07-19_06-48-20/create_user.sh' and '/home/ubuntu/backups/2023-07-19_06-48-20/create_user.sh' are the same file
Backup complete!
ubuntu@ip-172-31-91-254:~$ ls
backup.sh  backups
ubuntu@ip-172-31-91-254:~$ cd backups/
ubuntu@ip-172-31-91-254:~/backups$ ls -la
total 12
drwxrwxr-x 3 ubuntu ubuntu 4096 Jul 19 06:48 .
drwxr-x--- 6 ubuntu ubuntu 4096 Jul 19 06:48 ..
drwxrwxr-x 2 ubuntu ubuntu 4096 Jul 19 06:48 2023-07-19_06-48-20
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Lets understand the script</div>
</div>

To run this script, save it as [**backup.sh**](http://backup.sh) and then execute it from the terminal with the following command:

./[**backup.sh**](http://backup.sh)

This will create a backup directory in your current directory with the current date and time in the name. All files in the current directory will be recursively backed up to this directory.

Here is an explanation of the different parts of the script:

* The first line specifies that the script is a bash script.
    
* The second line gets the current working directory.
    
* The third line gets the date and time.
    
* The fourth line creates the backup directory.
    
* The fifth line recursively backups all files in the current directory to the backup directory.
    
* The sixth line prints a success message
    

---

***Task 3 : Read About Cron and Crontab, to automate the backup Script***

**Answer :**

**Cron and crontab are two terms that are often used together, but they have different meanings.**

* Cron is a **daemon**, or background process, that runs on Unix-like operating systems. It is responsible for executing commands at specific times or intervals.
    
* Crontab is a **file** that contains the schedule for cron jobs. It is a text file that is typically located in the user's home directory.
    

A cron job is a task that is scheduled to be run by a cron. Cron jobs can be used to perform a variety of tasks, such as:

* Sending email reminders
    
* Backing up files
    
* Launching web applications
    
* Updating software
    

To create a cron job, you need to create a crontab file and add a line that specifies the command that you want to run, the schedule for the job, and the user that the job should run as.

The syntax for a crontab line is as follows:

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">MINUTE HOUR DAY_OF_MONTH MONTH DAY_OF_WEEK COMMAND</div>
</div>

The different fields in the crontab line are as follows:

* MINUTE specifies the minute of the hour that the job should run.
    
* HOUR specifies the hour of the day that the job should run.
    
* DAY\_OF\_MONTH specifies the day of the month that the job should run.
    
* MONTH specifies the month that the job should run.
    
* DAY\_OF\_WEEK specifies the day of the week that the job should run.
    
* COMMAND specifies the command that you want to run.
    

For example, the following crontab line would run the command /path/to/command every day at 10:00 AM:

0 10 \* /path/to/comman

a crontab line that you can use to automate the backup script that we created earlier:

0 0 \* /path/to/[**backup.sh**](http://backup.sh/)

This crontab line will run the backup script every day at midnight. The 0 in the minute field specifies that the job should run at the beginning of the minute. The 0 in the hour field specifies that the job should run at the beginning of the hour. The \* in the day of the month, month, and day of the week fields specifies that the job should run every day.

To save this crontab line, you need to open your crontab file in a text editor. You can do this by running the following command:

crontab -e

Once you have opened your crontab file, you can paste the crontab line that we created above. Then, save the file and exit the text editor.

The next time that the crontab runs, it will execute the backup script. This will create a backup of all files in your current directory to a backup directory with the current date and time in the name.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>To automate backup using crontab</strong></div>
</div>

Check if your system has any crontab using in background :

**COPY**

```plaintext
ubuntu@ip-172-31-91-254:~$ crontab -l
# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
37 6 * * * ./backup
```

check if crontab done its work ,

**COPY**

```plaintext
Open backup file : 
cd ./backups/
ubuntu@ip-172-31-91-254:~/backups$ ls
2023-07-19_06-48-20
ubuntu@ip-172-31-91-254:~/backups$ cd 2023-07-19_06-48-20
ubuntu@ip-172-31-91-254:~/backups/2023-07-19_06-48-20$ ls
authorized_keys  backup.sh  create_user.sh  motd.legal-displayed
```

---

Task 4: ***User management in Linux is the process of creating, modifying, and deleting user accounts. User accounts are used to control who has access to a Linux system and what they can do.***

**Answer :**

There are two main types of user accounts in Linux:

* Regular users: These users are typically used by individuals to access the system. Regular users have a home directory, a shell, and a set of permissions that determine what they can do on the system.
    
* System users: These users are used by the system to perform tasks such as running daemons and services. System users typically have root privileges, which means they have complete control over the system.
    

There are a number of commands that can be used to manage user accounts in Linux. Some of the most common commands include:

* useradd : This command is used to create a new user account.
    
* usermod : This command is used to modify an existing user account.
    
* userdel : This command is used to delete a user account.
    
* passwd: This command is used to change the password for a user account.
    

In addition to these commands, there are also a number of graphical user interfaces (GUIs) that can be used to manage user accounts. Some of the most popular GUIs include:

* GNOME Control Center : This GUI is included in the GNOME desktop environment.
    
* KDE Control Center : This GUI is included in the KDE desktop environment.
    
* System Settings : This GUI is included in the Xfce desktop environment.
    

User management is an important part of system administration in Linux. By managing user accounts effectively, you can ensure that your system is secure and that users have the permissions they need to do their jobs.

Here are some of the benefits of good user management in Linux:

* Security: By carefully managing user accounts, you can help to protect your system from unauthorized access.
    
* Efficiency: By giving users the permissions they need to do their jobs, you can help to improve system efficiency.
    
* Compliance: By following industry best practices for user management, you can help to ensure that your system is compliant with regulations.
    

---

***task 5: Create 2 users and just display their Usernames***

**Answer :**

Creating users: To create a user using the useradd command, you need to run the following command:

**COPY**

```plaintext
useradd <username>
```

For example, to create a user named user1, you would run the following command:

**COPY**

```plaintext
useradd user1
```

To create a user using the GUI, you need to open the User Accounts application. This application is typically located in the System Settings menu. Once you have opened the User Accounts application, you can click on the Add User button to create a new user account.

When you create a user account using the GUI, you will be prompted to enter a username, password, and other information about the user.

Once you have created a user account, you can log in to the account using the username and password that you created.

Here are some of the most common options for the useradd command:

* \-m : Create a home directory for the user.
    
* \-d : Specify the home directory for the user.
    
* \-s : Specify the default shell for the user.
    
* \-u : Specify the user ID for the user.
    
* \-g : Specify the group ID for the user.
    
* \-c : Specify a comment for the user.
    
* \-G : Specify a list of groups for the user to belong to.
    

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">add 2 users and display</div>
</div>

**COPY**

```plaintext
ubuntu@ip-172-31-91-254:~$ cd  /
ubuntu@ip-172-31-91-254:~$ sudo useradd -m user1 
ubuntu@ip-172-31-91-254:~$ sudo useradd -m user2
ubuntu@ip-172-31-91-254:~$ cat etc/passwd
cat: etc/passwd: No such file or directory
ubuntu@ip-172-31-91-254:~$ cd /etc
ubuntu@ip-172-31-91-254:/etc$ cat passwd
root:x:0:0:root:/root:/bin/bash
*
*
user1:x:1001:1001::/home/user1:/bin/sh
user2:x:1001:1001::/home/user1:/bin/sh
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>the code to create 2 users and display their usernames in Linux:</strong></div>
</div>

**COPY**

```plaintext
#!/bin/bash
# Create the first user
sudo useradd -m -d /home/user1 -s /bin/bash user1
# Create the second user
sudo useradd -m -d /home/user2 -s /bin/bash user2
# Display the usernames
echo "The usernames are: user1 and user2"
```

To run this code, you can save it as create\_[**users.sh**](http://users.sh/) and then execute it from the terminal with the following command:

./create\_[**users.sh**](http://users.sh/)

**COPY**

```plaintext
ubuntu@ip-172-31-91-254:~$ vim create_user.sh
ubuntu@ip-172-31-91-254:~$ chmod 777 create_user.sh
ubuntu@ip-172-31-91-254:~$ ./create_user.sh
ubuntu@ip-172-31-91-254:~$ cd /etc
ubuntu@ip-172-31-91-254:/etc$ cat passwd
root:x:0:0:root:/root:/bin/bash
*
user1:x:1001:1001::/home/user1:/bin/sh
user2:x:1002:1002::/home/user2:/bin/bash
```

This will create two users, user1 and user2, and then display their usernames.

Here is an explanation of the different parts of the code:

* The first line specifies that the script is a bash script.
    
* The second line creates the first user. The useradd command is used to create a new user. The -m option specifies that the user should be created with a home directory. The -d option specifies the home directory for the user. The -s option specifies the default shell for the user.
    
* The third line creates the second user. The useradd command is used to create a new user. The -m option specifies that the user should be created with a home directory. The -d option specifies the home directory for the user. The -s option specifies the default shell for the user.
    
* The fourth line displays the usernames. The echo command is used to display a message. The usernames variable is a list of the usernames that were created.
    

Conclusion: Shell scripting saves time, reduces errors, and improves system reliability. With shell scripts, system administrators can automate various tasks, such as monitoring disk usage, managing user accounts, creating backups, and more. By automating system administration tasks, they can enhance efficiency, reduce downtime, and improve overall system security.

Get started with shell scripting today, and unleash the power of automation on your Linux systems! 🚀💻
