653-401无法在shell脚本中使用mv重命名

时间:2013-07-11 16:02:34

标签: shell ksh

这段代码似乎有什么问题

#/usr/bin/ksh
RamPath=/home/RAM0
RemoteFile=Site Information_2013-07-11-00-01-56.CSV

cd $RamPath
newfile=$(echo "$RomoteFile" | tr ' ' '_')
mv  "$RemoteFile" "$newfile"

运行脚本后出现错误:

mv网站信息_2013-07-11-00-01-56.CSV  至:653-401无法重命名站点信息_2013-07-11-00-01-56.CSV              路径名中的文件或目录不存在。

目录中存在该文件。我也在变量中加了双引号。上面的错误相同。

oldfile=$(echo "$RemoteFile" | sed 's/^/"/;s/$/"/' | sed 's/^M//')
newfile=$(echo "$RomoteFile" | tr ' ' '_')
mv  "$RemoteFile" "$newfile"

1 个答案:

答案 0 :(得分:0)

至少有两个问题:

  1. 该脚本在变量名中有拼写错误,如@shelter建议的那样。
  2. 应引用分配给变量的值。
  3. <强>错字

    newfile=$(echo "$RomoteFile" | tr ' ' '_') # returns an empty string
    mv  "$RemoteFile" "$newfile"
    

    shell是一种非常宽松的语言。错字很容易制作。

    捕获它们的一种方法是强制取消设置变量的错误。 -u选项就是这样做的。在脚本顶部添加set -u,或使用ksh -u scriptname运行脚本。

    另一种为每个变量单独测试它的方法,但它会给你的代码增加一些开销。

    newfile=$(echo "${RomoteFile:?}" | tr ' ' '_')
    mv  "${RemoteFile:?}" "${newfile:?}"
    

    如果变量${varname:?[message]}未设置或为空,则ksh和bash中的varname构造将生成错误。

    变量分配

    这样的作业
    varname=word1 long-string
    

    必须写成:

    varname="word long-string"
    

    否则,它将在为命令 varname=word创建的环境中作为作业long-string读取。

    $ RemoteFile=Site Information_2013-07-11-00-01-56.CSV
    -ksh: Information_2013-07-11-00-01-56.CSV: not found [No such file or directory]
    $ RemoteFile="Site Information_2013-07-11-00-01-56.CSV"
    

    作为奖励,ksh允许您使用${varname//string1/string2}方法在变量扩展期间替换字符:

    $ newfile=${RemoteFile// /_}
    $ echo "$newfile"
    Site_Information_2013-07-11-00-01-56.CSV
    

    如果您是(korn)shell编程的新手,请阅读手册页,尤其是有关参数扩展和变量的部分。

相关问题