linux - Linux脚本抛出错误,虽然它看起来完全正常
问题描述
我必须为以下问题编写 Linux 脚本
Write a script that renames files based on the file extension. The script should prompt the user for a file extension.
Next, it should ask the user what prefix to prepend to the file name(s). By default the prefix should be the current date in YYYYMMDD format.
So, if the user simply presses enter the date will be used. Otherwise, whatever the user entered will be used as the prefix.
Next, it should display the original file name and the new name of the file. Finally, it should rename the file.
我在下面写了 shell 脚本及其抛出错误。对我来说,脚本看起来完全没问题。虽然我可以编写替代脚本,但有人可以在这个脚本中提出错误的原因和解决方案。
脚本:
#!/bin/bash
read -p "Please enter a file extension : " EXT
for f in *.${EXT}
do
read -p "Please enter a file prefix (Press ENTER to prefix current Date) :" PREFIX
if [ -z "PREFIX" ]
then
new = "$(date +"%Y-%M-%d")-$(basename ${f})"
mv $f $new
echo "$f renamed to $new"
else
new = "${PREFIX}-${f}"
mv $f $new
echo "$f renamed to $new"
fi
done
错误 :
./new.sh: line 13: new: command not found
BusyBox v1.24.2 (2017-05-25 17:33:59 CEST) multi-call binary.
Usage: mv [-fin] SOURCE DEST
or: mv [-fin] SOURCE... DIRECTORY
Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY
-f Don't prompt before overwriting
-i Interactive, prompt before overwrite
-n Don't overwrite an existing file
*.png renamed to
[root@localhost ~]#
[root@localhost ~]#
解决方案
在分配过程中,空格会破坏您的脚本
#new = "$(date +"%Y-%M-%d")-$(basename ${f})"
new="$(date +"%Y-%M-%d")-$(basename ${f})"
还
#new = "${PREFIX}-${f}"
new="${PREFIX}-${f}"
shellcheck是用于基本 shell 检查的优秀工具
推荐阅读
- c++ - 如何获取 QNetworkConfiguration UserChoice 对话框?
- c++ - 将字符向量转换为单个字符串
- c# - ScrollViewer 在没有固定高度的情况下不显示滚动远
- java - Project Reactor 的 Flux 在处理错误期间获取失败项目
- angular - 仅当第一个 Promise 出错时,我如何返回不同的 Promise?
- mysql - 同一张表上的相同类型查询需要不同的时间来执行 MySQL
- java - OpenGL 向上运动
- r - 将虚拟数据帧转换为数据帧
- bash - 在带有切割器的打印机中从 shell 脚本打印多页文件
- javascript - Cloud Functions (Firebase) - 通过部分加载 Firebase 模块来减少冷启动时间?