You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求修正Bash脚本:实现单文件批量克隆并添加序列后缀

Got it, let's fix this script properly to meet your exact need! Your original snippet has a few issues (like targeting sequence numbers instead of your actual file, syntax gaps, and undefined variables) — here's a polished version that does exactly what you want:

Fixed Bash Script for Cloning Your File
#!/bin/bash

# Define your directories clearly
SOURCE_DIR="/home/foo"
TARGET_DIR="/home/foo/cloned_files"

# Make sure the target folder exists (no errors if it's already there)
mkdir -p "$TARGET_DIR"

# Grab the single file in your source directory (skip the target folder itself)
ORIGINAL_FILE=$(find "$SOURCE_DIR" -maxdepth 1 -type f | head -n 1)

# Quick check to make sure we actually found a file
if [ -z "$ORIGINAL_FILE" ]; then
    echo "Oops: No file found in $SOURCE_DIR"
    exit 1
fi

# Pull just the filename (without the path)
FILE_NAME=$(basename "$ORIGINAL_FILE")

# Loop through 01-10 and copy the file with the numbered suffix
for seq_num in $(seq -w 01 10); do
    cp "$ORIGINAL_FILE" "$TARGET_DIR/${FILE_NAME}.$seq_num"
done

echo "Done! 10 cloned files are in $TARGET_DIR"

What makes this work better?

  • mkdir -p: Creates the target directory (and parent folders if needed) without throwing errors if it already exists.
  • Reliable file detection: Uses find instead of ls to safely grab the single file in your directory, avoiding accidental matches with folders.
  • basename: Extracts just your original filename (like xfile.txt) instead of the full path, so the cloned filenames look clean.
  • seq -w: Generates padded numbers (01, 02...10) to keep your filenames consistent and ordered.
  • cp instead of cat: Copies the file directly, preserving its permissions and metadata (way better than redirecting file content).

Super-simplified version (if you're 100% sure the source dir only has your file)

If you don't need error checking and want something shorter:

#!/bin/bash
cd /home/foo || exit
mkdir -p cloned_files
original_file=$(ls -1)
for num in $(seq -w 01 10); do
    cp "$original_file" "cloned_files/${original_file}.$num"
done

内容的提问来源于stack exchange,提问作者user2585000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:11:35