根据用户输入移动文件的 Bash 脚本

根据用户输入移动文件的 Bash 脚本

我对 Bash 和编码还不熟悉,说实话,我需要帮助完成一项家庭作业,其中需要编写一个脚本,要求用户输入文件名,然后将其移动到指定位置。

我认为实际移动文件的脚本是

#!/bin/bash
mv /path/to/source /path/to/destination

但是,当要求用户输入希望移动的文件名以及要将其移动到的位置时,我该如何实现这一点?

我正在使用通过 VirtualBox 安装的 Ubuntu。

答案1

基本上,脚本会要求提供文件路径,然后要求提供放置文件的文件夹:

#!/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 ||)

相关内容