bat复制文件到指定目录同名_Bash技巧:介绍一个批量复制文件到指定目录的Shell脚本
时间: 2023-09-13 09:05:00 浏览: 50
下面是一个 Bash 脚本示例,可以将指定目录下的所有同名文件复制到另一个目录:
```bash
#!/bin/bash
# 源文件目录
src_dir="/path/to/source/directory"
# 目标目录
dest_dir="/path/to/destination/directory"
# 复制所有同名文件
for file in "$src_dir"/*; do
if [[ -f "$file" ]]; then
filename=$(basename "$file")
cp "$src_dir/$filename" "$dest_dir/$filename"
fi
done
```
将上述代码保存为 `copy.sh`,然后在终端中执行 `bash copy.sh` 即可运行脚本。请确保将 `src_dir` 和 `dest_dir` 变量替换为实际的目录路径。此脚本将复制 `src_dir` 中的所有同名文件到 `dest_dir` 目录中,如果目标目录中已经存在同名文件,则会被覆盖。
相关问题
编写一个Shell脚本,将指定目录下的所有文件复制到另一个目录中
以下是将指定目录下的所有文件复制到另一个目录中的Shell脚本:
```shell
#!/bin/bash
# 指定源目录和目标目录
src_dir=/path/to/source/directory
dst_dir=/path/to/destination/directory
# 如果目标目录不存在,则创建目标目录
if [ ! -d $dst_dir ]; then
mkdir -p $dst_dir
fi
# 遍历源目录下的所有文件,将其复制到目标目录中
for file in $src_dir/*
do
cp $file $dst_dir
echo "已复制文件 ${file} 到 ${dst_dir} 目录中"
done
echo "[ 文件复制完成 ]"
```
写一个shell脚本,每60分钟复制当前目录下的一份随机文件到指定目录
#!/bin/bash
# 设置复制的源目录和目标目录
src_dir=$(pwd)
dest_dir="/path/to/destination/directory/"
# 定义函数,用于随机选择一个文件并复制到目标目录
copy_random_file() {
# 获取当前目录下所有文件列表
files=$(ls $src_dir)
# 随机选择一个文件
random_file=$(echo "$files" | shuf -n 1)
# 复制文件到目标目录
cp "$src_dir/$random_file" "$dest_dir"
}
# 循环执行函数,每60分钟执行一次
while true
do
copy_random_file
sleep 3600
done
# 注意:为了使脚本能够在后台运行,可以使用nohup命令,例如:
# nohup ./script.sh &