我必须为以下问题编写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 ~]#
答案 0 :(得分:2)
空格在分配过程中破坏了脚本
#new = "$(date +"%Y-%M-%d")-$(basename ${f})"
new="$(date +"%Y-%M-%d")-$(basename ${f})"
也
#new = "${PREFIX}-${f}"
new="${PREFIX}-${f}"
shellcheck是用于基本shell检查的出色工具