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

bash假删除脚本无法处理含空格文件名问题求助

解决Bash脚本处理含空格文件名的问题

你的脚本无法正确处理带空格的文件名,核心原因是未对变量和特殊参数进行引号包裹——Bash在遇到未加引号的变量/参数扩展时,会自动按空白字符(空格、制表符等)分词,把单个带空格的文件名拆分成多个独立参数处理。

修改后的完整脚本

#!/usr/bin/env bash

trashbin="$HOME/trashbin"

function usage() {
    echo "usage : $0 file ..."
    echo "moves files to $trashbin"
    echo "creates $trashbin if it doesn't exist"
    exit -1
}

# Error if no arguments
if (( $# < 1 )); then
    usage
fi

# Create directory if it doesn't exist
if [[ ! -d "$trashbin" ]]; then
    mkdir "$trashbin"
fi

for i in "$@"; do
    name="$(basename "$i")"
    mv "$i" "$trashbin/$name"
done

关键修改说明

  • for i in "$@":"$@"是Bash的特殊参数,加引号后会完整保留每个传入参数的原始形式(包括带空格的文件名),确保每个文件名作为单独的循环项处理,不会被拆分。
  • basename "$i":给$i添加双引号,避免basename将带空格的文件名误判为多个输入参数。
  • mv "$i" "$trashbin/$name":对源文件路径$i加引号,保证Bash识别完整的文件名;目标路径采用引号包裹的变量拼接,是应对特殊字符的通用安全写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:01:11