Shell 脚本 - 使用 sh 的 运行 脚本错误替换错误

Shell script - Bad substitution Error while running script with sh

我正在尝试在目录中循环并使用 space 重命名文件名。但是我在 运行 使用 sh test.sh

时遇到了错误的替换错误
#!/bin/bash
for f in /home/admin1/abc/*.kmz
do
mv "$f" "${f// /_}"
#rm $i
done

因为我需要在 crontab 中配置,所以我可能需要 运行 使用 sh 命令而不是 ./

Bourne Shell sh 不支持此类替换。您可以 运行 这个脚本:

for f in /home/admin1/abc/*.kmz
do
  mv "$f" `echo "$f" |tr ' ' _`
done

要使我的评论成为答案:

您是 运行 sh,但您的脚本声明它是 bash 脚本。在许多系统上 sh 不是 bash,而是一个不支持所有 bashisms 的更轻的 shell。

或者

  • 运行 与 bash test.sh
  • 标记文件 chmod u+x 和 运行 ./test.sh 以使用 shebang 行。