且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

linux bash脚本创建文件夹并移动文件

更新时间:2023-12-05 18:24:22

#!/usr/bin/env bash

# Enable bash built-in extglob to ease file matching.
shopt -s extglob
# To deal with the case where nothing matches. (courtesy of  mklement0)
shopt -s nullglob

# A pattern to match files with specific file extensions.
# Example for matching additional file types.
#match="*+(jpg|.png|.gif)"
match="*+(.jpg)"

# By default use the current working directory.
src="${1:-.}"
dest="${2:-/root/Desktop/My_pictures/}"

# Pass an argument to this script to name the subdirectory
# something other than picture.
subdirectory="${3:-picture}"

# For each file matched
for file in "${src}"/$match
do
  # make a directory with the same name without file extension
  # and a subdirectory.
  targetdir="${dest}/$(basename "${file%.*}")/${subdirectory}"
  # Remove echo command after the script outputs fit your use case. 
  echo mkdir -p "${targetdir}"
  # Move the file to the subdirectory.
  echo mv "$file" "${targetdir}"
done