0% found this document useful (0 votes)
37 views11 pages

Shell Script to Simulate File Commands

linux

Uploaded by

Sathya Ashok
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views11 pages

Shell Script to Simulate File Commands

linux

Uploaded by

Sathya Ashok
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Write a shell script to stimulate the file commands: rm, cp, cat, mv, cmp, wc, split, diff.

#!/bin/bash

# Function to simulate the rm command

simulate_rm() {

read -p "Enter the file name to remove: " file

if [ -f "$file" ]; then

rm "$file"

echo "File '$file' removed."

else

echo "File '$file' not found."

fi

# Function to simulate the cp command

simulate_cp() {

read -p "Enter the source file name: " source

read -p "Enter the destination file name: " destination

if [ -f "$source" ]; then

cp "$source" "$destination"

echo "File copied from '$source' to '$destination'."

else

echo "Source file '$source' not found."

fi

# Function to simulate the cat command

simulate_cat() {

read -p "Enter the file name to display: " file

if [ -f "$file" ]; then

cat "$file"

else
echo "File '$file' not found."

fi

# Function to simulate the mv command

simulate_mv() {

read -p "Enter the source file name: " source

read -p "Enter the destination file name: " destination

if [ -f "$source" ]; then

mv "$source" "$destination"

echo "File moved/renamed from '$source' to '$destination'."

else

echo "Source file '$source' not found."

fi

# Function to simulate the cmp command

simulate_cmp() {

read -p "Enter the first file name: " file1

read -p "Enter the second file name: " file2

if [ -f "$file1" ] && [ -f "$file2" ]; then

cmp "$file1" "$file2"

else

echo "One or both files not found."

fi

# Function to simulate the wc command

simulate_wc() {

read -p "Enter the file name to count words, lines, and characters: " file

if [ -f "$file" ]; then

wc "$file"
else

echo "File '$file' not found."

fi

# Function to simulate the split command

simulate_split() {

read -p "Enter the file name to split: " file

read -p "Enter the number of lines per split: " lines

if [ -f "$file" ]; then

split -l "$lines" "$file"

echo "File '$file' split into parts with $lines lines each."

else

echo "File '$file' not found."

fi

# Function to simulate the diff command

simulate_diff() {

read -p "Enter the first file name: " file1

read -p "Enter the second file name: " file2

if [ -f "$file1" ] && [ -f "$file2" ]; then

diff "$file1" "$file2"

else

echo "One or both files not found."

fi

# Display menu and get user's choice

echo "Please select a command to simulate:"

echo "1. rm (Remove a file)"

echo "2. cp (Copy a file)"


echo "3. cat (Display file content)"

echo "4. mv (Move/Rename a file)"

echo "5. cmp (Compare two files)"

echo "6. wc (Count lines, words, and characters in a file)"

echo "7. split (Split a file into smaller parts)"

echo "8. diff (Compare the differences between two files)"

echo "9. Exit"

# Read user's choice

read -p "Enter your choice [1-9]: " choice

# Execute the appropriate function based on the user's choice

case $choice in

1)

simulate_rm

;;

2)

simulate_cp

;;

3)

simulate_cat

;;

4)

simulate_mv

;;

5)

simulate_cmp

;;

6)

simulate_wc

;;

7)
simulate_split

;;

8)

simulate_diff

;;

9)

echo "Exiting..."

exit 0

;;

*)

echo "Invalid choice. Please run the script again and select a valid option."

;;

esac

Explanation:

1. Functions:

o Each function simulates a basic file operation command:

 simulate_rm(): Simulates the rm command.

 simulate_cp(): Simulates the cp command.

 simulate_cat(): Simulates the cat command.

 simulate_mv(): Simulates the mv command.

 simulate_cmp(): Simulates the cmp command.

 simulate_wc(): Simulates the wc command.

 simulate_split(): Simulates the split command.

 simulate_diff(): Simulates the diff command.

2. Menu:

o The script presents a menu with options corresponding to each of the simulated commands.

3. User Input:

o The script reads the user's choice and calls the corresponding function.

4. Exit Option:

o The user can choose to exit the script by selecting option 9.

Usage:

 Save the script to a file, e.g., simulate_file_commands.sh.


 Make it executable: chmod +x simulate_file_commands.sh.

 Run the script: ./simulate_file_commands.sh.

The script will display a menu, allowing you to simulate the selected file operations.

#!/bin/bash

# Display currently logged user and his log name

echo "Currently logged user and log name:"

whoami

echo

# Display current shell, home directory, OS type, current Path setting, and current working directory

echo "Current shell: $SHELL"

echo "Home directory: $HOME"

echo "Operating System type: $(uname -s)"

echo "Current Path setting: $PATH"

echo "Current working directory: $(pwd)"

echo

# Show currently logged number of users

echo "Currently logged number of users:"

who | wc -l

echo

# Show all available shells

echo "Available shells:"

cat /etc/shells

echo

# Show CPU information (processor type and speed)


echo "CPU information:"

lscpu | grep 'Model name\|CPU MHz'

echo

# Show memory information

echo "Memory information:"

free -h

 whoami prints the currently logged-in user.

 $SHELL, $HOME, uname -s, $PATH, and pwd are used to display the respective details.

 who | wc -l counts the number of currently logged-in users.

 cat /etc/shells lists all available shells.

 lscpu provides CPU information, with grep used to filter relevant details.

 free -h shows memory usage in a human-readable format.

shell script that allows the user to choose between displaying the current date, user name, file listing, or directories:

#!/bin/bash

# Function to display the current date

display_date() {

echo "Current Date and Time: $(date)"

# Function to display the current user name

display_user() {

echo "User Name: $(whoami)"

# Function to list files in the current directory

list_files() {

echo "Files in the current directory:"

ls -p | grep -v / # Lists files only, excluding directories

}
# Function to list directories in the current directory

list_directories() {

echo "Directories in the current directory:"

ls -d */ # Lists directories only

# Display menu and get user's choice

echo "Please select an option:"

echo "1. Display Current Date"

echo "2. Display User Name"

echo "3. List Files in Current Directory"

echo "4. List Directories in Current Directory"

echo "5. Exit"

# Read user's choice

read -p "Enter your choice [1-5]: " choice

# Execute the appropriate function based on the user's choice

case $choice in

1)

display_date

;;

2)

display_user

;;

3)

list_files

;;

4)

list_directories

;;
5)

echo "Exiting..."

exit 0

;;

*)

echo "Invalid choice. Please run the script again and select a valid option."

;;

Esac

How the Script Works:

1. Function Definitions:

o display_date(): Prints the current date and time.

o display_user(): Prints the current logged-in user's name.

o list_files(): Lists all files in the current directory (excluding directories).

o list_directories(): Lists all directories in the current directory (excluding files).

2. Menu:

o The script presents a menu with options for the user to choose from.

3. User Choice:

o The script reads the user's choice and uses a case statement to execute the corresponding function.

o If the user selects an invalid option, the script notifies them and exits.

4. Exit Option:

o The user can choose to exit the script by selecting option 5.

Usage:

 Save the script to a file, e.g., menu_script.sh.

 Make it executable: chmod +x menu_script.sh.

 Run the script: ./menu_script.sh.

The script will display a menu, and based on the user's choice, it will perform the corresponding action.

4o

5. Write a Shell script for displaying current date, user name, file listing and directories by getting user choice.
#!/bin/bash

# Function to display the current date


show_date() {
echo "Current date and time: $(date)"
}
# Function to display the user name
show_user() {
echo "Current user: $(whoami)"
}

# Function to list files in the current directory


list_files() {
echo "Listing files in the current directory:"
ls -p | grep -v /
}

# Function to list directories in the current directory


list_directories() {
echo "Listing directories in the current directory:"
ls -p | grep /
}

# Main script starts here


echo "Please choose an option:"
echo "1. Display current date and time"
echo "2. Display user name"
echo "3. List files"
echo "4. List directories"
echo "5. Exit"

# Read user choice


read -p "Enter your choice (1-5): " choice

case $choice in
1)
echo "Current date and time: $(date)"
;;
2)
echo "Current user: $(whoami)"
;;
3)
echo "Listing files in the current directory:"
ls -p | grep -v
;;
4)
echo "Listing directories in the current directory:"
ls -p | grep /
;;
5)
echo "Exiting..."
exit 0
;;
*)
echo "Invalid choice. Please enter a number between 1 and 5."
;;
esac

Common questions

Powered by AI

The script manages file and directory listings with separate functions that utilize the ls command. Files are listed using ls -p | grep -v /, which lists items excluding directories . Directory listing uses ls -p | grep /, filtering to show only directories. This separation uses the -p flag, which appends a '/' to directory results from ls, allowing grep to filter accordingly.

The script interacts with the user by displaying a menu and prompts the user to enter their choice or input file names for operations . Improvements in usability could include adding validation to ensure inputs are valid file paths and numbers before processing, providing clear error messages, and optionally including an interactive help option to guide the user. Enhanced error handling could detect and handle permissions errors or non-existent files more gracefully, prompting the user for correction instead of just exiting or displaying an error message.

Using shell scripts allows for automation and batch processing of multiple file operations with consistent logic and interaction handling . This approach provides users the ability to script repetitive tasks, offer user interfaces through menus, and potentially enhance safety by implementing checks and confirmations. Conversely, direct terminal commands give immediate execution control, flexibility, and speed for experienced users, avoiding the overhead of script processing. However, this lacks the automation and repeatability advantages scripts offer, and users must manually handle each operation, which can lead to human error.

Security considerations for shell scripts involving file manipulation include ensuring scripts are executed with least privilege, minimizing the risk of data loss through strict input validation, and implementing confirmation prompts, especially for destructive actions like rm . Additionally, incorporating logging to track changes, allowing for reversible actions where possible, and using appropriate permissions and ownership settings to protect the script against tampering or misuse are vital. Scripts should also be tested in a controlled environment to prevent unintended system changes.

The chmod +x command changes the permission of the script to make it executable . It is necessary because without setting the executable permission, the script cannot be run directly from the command line. The chmod command adjusts the file’s permissions, allowing the user to execute it as a program, which is essential for the script to function as intended.

The shell script simulates the rm command by prompting the user for the file name to remove and then using the rm command to delete it if it exists . The potential implications include the permanent deletion of critical system files or user data if the script is executed with improper permissions or user input. Therefore, it's important to ensure that the script is run with appropriate checks and possibly include interactive confirmations to mitigate accidental deletions.

The script handles user errors primarily through basic conditional checks and simple error messages when invalid inputs are entered or files are not found . Enhancements to improve robustness could include multi-stage validation, offering suggestions for correct input, implementing retries, and detailed contextual error messages guiding the user to correct the error. Advanced handling could also include logging errors for diagnosis, providing a help menu for common issues, and employing environment checks to ensure the script is being run in a supported configuration.

The advantages of using a shell script for simulating file commands include providing a controlled environment for learning, testing without affecting actual files directly, and integrating multiple operations in a cohesive workflow . However, potential drawbacks include the risk of user error leading to incorrect file operations, limited error handling, and additional overhead of scripting for operations that could be directly executed with native commands. Additionally, the abstraction may introduce misunderstandings about the actual behavior of these commands when run outside the script context.

The script simulates the diff command by allowing the user to enter the names of two files, checking if both files exist, and then using the diff command to compare them . This functionality is important in file management as it helps identify differences between files, which is crucial in version control, ensuring data consistency, and troubleshooting by comparing configuration files.

Scripting shell command simulations offers significant educational value by allowing new Unix/Linux users to safely experiment with commands in a controlled environment without immediate risk to the system or user files . This practice helps in understanding command syntax, developing problem-solving skills by debugging scripts, learning about script execution environment effects, and gaining confidence in using shell programs. It also introduces users to concepts of automation and scripting logic, which can be applied to more complex tasks as their skills advance.

You might also like