Backup and explorer
Task 1:
Upon execution without any command-line arguments, the script will display a welcome message and list all the files and directories in the current path.
For each file and directory, the script will print its name and size in human-readable format (e.g., KB, MB, GB). This information will be obtained using the ls command with appropriate options.
The list of files and directories will be displayed in a loop until the user decides to exit the explorer.
Task 2:
After displaying the file and directory list, the script will prompt the user to enter a line of text.
The script will read the user's input until an empty string is entered (i.e., the user presses Enter without any text).
For each line of text entered by the user, the script will count the number of characters in that line.
The character count for each line entered by the user will be displayed.
Solution :
#!/bin/bash
while true
do
# Task 1
# Welcome message
echo "Hello good morning, time to get started."
echo "Here are your files and directories."
# commad to display all the files and directories in the pwd
ls -lh | awk '{print $9,"(",$5,")"}' | tail -n +2
# Task 2
while true; do
# take input from the user
echo "Enter a string:"
read string
# if length ${#string} is equal to 0 exit the while loop
if (( ${#string} == 0 ));then
break
fi
# display the no. of characters in the string
echo "$string" | wc -m
done
# stop the while loop is user want to exit
echo "Do you want to exit ?"
read input
if (( $input == "yes" ));then
break
fi
done
echo "Good bye."
Output :
Task 3 :
Your task is to create a bash script that takes a directory path as a command-line argument and performs a backup of the directory. The script should create timestamped backup folders and copy all the files from the specified directory into the backup folder.
Solution :
#!/bin/bash
source=$1
time_stamp=$(date +"%Y-%m-%d-%H-%M-%S")
directory=$(pwd)
destination="$directory/backup_$time_stamp"
mkdir -p "$destination"
cp -r "$source"/* "$destination"
if [ $? -eq 0 ] ;then
echo "Backup successful"
else
echo "Backup Failed"
fi
Output :
Subscribe to my newsletter
Read articles from Bharat directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by