首页 > 解决方案 > 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 YYYY­MM­DD 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 ~]#

标签: linux

解决方案


在分配过程中,空格会破坏您的脚本

#new = "$(date +"%Y-%M-%d")-$(basename ${f})"
new="$(date +"%Y-%M-%d")-$(basename ${f})"

#new = "${PREFIX}-${f}"
new="${PREFIX}-${f}"

shellcheck是用于基本 shell 检查的优秀工具


推荐阅读