交互式脚本如何将多个文件从一个目录移动到另一个目录?

交互式脚本如何将多个文件从一个目录移动到另一个目录?

我正在尝试编写一个 shell 脚本,将一个目录中的多个文件移动到另一个目录。我可以编写一个脚本,询问用户他们想要移动哪个文件,然后将该文件移动到目标目录,但是我如何将多个文件移动到另一个目录呢?

这是我为用户移动一个文件到另一个目录编写的脚本:

#! /bin/bash
echo " enter the name of the file that you want to move "
read filename
if [ -f "$filename" ]
then
 echo " enter the target directoy name that you want to move the file to"
 read dir
if [ -d "$dir" ]
then
 mv -i "$filename" "$dir" && echo "the file is moved to "$dir" successfully "                  

else echo "未找到目录" fi else echo "未找到文件!"
exit 1 fi

答案1

该脚本循环遍历当前目录中的所有文件,并要求移动到指定目录:

#!/usr/bin/env bash

set -e

read -p "enter the target directoy name:" -r dir
if [[ ! -d "$dir" ]];then
  echo "incorrect directory"
  exit 1
fi
if [[ ! -w "$dir" ]];then
  echo "directory is not writeable by current user"
  exit 1
fi

for filename in ./*; do
  [[ ! -w $filename ]] && echo "$filename cant be moved, access denied" && continue
  read -p "move $filename to directory? [y/Enter=No]" domove
  [[ ! -z "$domove" ]] && mv -i "$filename" "$dir" && echo "$filename moved successfully" || true
done

相关内容