Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- #------------------------------------------------------------------------------
- # [Dylan Foster] Swap or Not
- # The purpose of this assignment is to compare the names of two
- # files and swap the files if they are not identical.
- #------------------------------------------------------------------------------
- file1=$1
- file2=$2
- function debug {
- echo "*******************************"
- echo "* $file1" "is currently this *"
- echo "* $file2" "is currently this *"
- echo "*******************************"
- }
- # Function to show the usage message
- function show_usage {
- echo "USAGE: > bash swap.sh file1 file2"
- }
- # Function to show inability to swap
- function show_error {
- echo "Cannot perform swap, please check files"
- echo "------------------------------------------------------------"
- exit 1
- }
- # Function to swap files
- function swap {
- if [ "$file1" != "$file2" ]; then
- #debug
- local TMPFILE=tmp.$$
- mv "$file1" $TMPFILE
- mv "$file2" "$file1"
- mv $TMPFILE "$file2"
- echo "$file1" "swapped with" "$file2" >> log.txt
- echo "$file1" "swapped with" "$file2"
- echo "------------------------------------------------------------"
- exit 0
- else
- show_usage
- show_error
- exit 1
- fi
- }
- # If no arguments are passed, prompt the user for arguments
- if [ $# -eq 0 ]; then
- #debug
- echo -n "Enter two files you want to swap > "
- read file1 file2
- debug
- fi
- # If only the first file is supplied
- if [ $# -eq 1 ]; then
- echo "The second filename was not supplied"
- show_usage
- show_error
- fi
- # If more than two files are input
- if [ $# -gt 2 ]; then
- echo "More than two files are supplied"
- show_usage
- show_error
- fi
- # Checks to see if the files exist
- if [[ ! -e "$1" ]]; then
- echo "$1" "does not exist"
- #debug
- show_error
- elif [[ ! -e "$2" ]]; then
- echo "$2" "does not exist"
- #debug
- show_error
- fi
- # Check if files are both readable
- if [[ ! -r "$file1" ]]; then
- echo "$file1" "is not readable"
- show_error
- elif [[ ! -r "$file2" ]]; then
- echo "$file2" "is not readable"
- show_error
- fi
- # Check if files are both writable
- if [[ ! -w "$file1" ]]; then
- echo "$file1" "is not writable"
- show_error
- elif [[ ! -w "$file2" ]]; then
- echo "$file2" "is not writable"
- show_error
- fi
- # Check if files are both executable
- if [[ ! -x "$file1" ]]; then
- echo "$file1" "is not executable"
- show_error
- elif [[ ! -x "$file2" ]]; then
- echo "$file2" "is not executable"
- show_error
- fi
- #------------------------------------------------------------------------------
- # Executes swap method if all checks are clear
- swap
- #------------------------------------------------------------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement