Bash script for moving files based on user input
I'm new to Bash and coding in general and not gonna lie I need help for a homework task in which a script needs to be made that asks the user for a file name, and then moves it to a designated location.
I assume the script for actually moving the file would be
#!/bin/bash
mv /path/to/source /path/to/destination
But how do I implement this when asking the user to enter the file name the wish the move, and the location they want to move it to?
I'm using Ubuntu installed with VirtualBox.
Solution 1:
Basically the script would ask for a file path and then for a folder to put the file in:
#!/bin/bash
#set the variable "file" to empty
unset file
#keep asking until (= until loop) the variable is filled with a path to a file
until [[ -f "$file" ]]
do
#ask the user to enter a file and save what is entered in the variable "file"
read -rp "Please give the path to a file: " file
done
#now do the same for the destination folder but keep asking until the entered string is an existing valid folder
unset folder
until [[ -d "$folder" ]]
do
read -rp "Please give the path to a folder to put the file in: " folder
done
#the variables "file" and "folder" are now filled with valid paths so move the file
mv "$file" "$folder" \ #the "\" means "move on to the next line but treat it as one big line"; just easier for readability
&& echo "Moved $file to $folder" \ #run this when the mv command succeeded (because of the &&)
|| echo "Failed to move $file to $folder" #run this when the mv command failed (because of the ||)