你的脚本有几个地方需要改进来处理包含空格的参数。主要问题在于变量引用时缺少双引号。让我帮你分析并提供改进版本:
$title 和 $file 在条件判断和命令中没有用双引号包围mv 和 perl 命令的参数没有正确引用ls 命令可能返回多个文件时会有问题#!/bin/bash
title="$1"
file=$(ls ~/Downloads/*.html 2>/dev/null | head -n 1)
if [ -z "$title" ]; then
echo "no title"
exit 1
fi
if [ -z "$file" ]; then
file=$(ls ~/Downloads/*.pdf 2>/dev/null | head -n 1)
if [ -z "$file" ]; then
echo "no html|pdf"
exit 1
fi
fi
filename=$(basename "$file")
mv "$file" .
perl create-article.pl "$filename" "$title"
"$title"、"$file"2>/dev/null 来抑制 ls 的错误输出head -n 1 确保只取第一个匹配的文件exit 1 而不是 exit 来明确表示错误这样修改后,你的命令 ./script.sh "a title for my article" 就能正常工作了。双引号确保了包含空格的标题作为一个完整的参数传递给脚本和 Perl 程序。