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

653-401无法在shell脚本中使用mv重命名,shell,ksh,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-0

这个代码有什么问题

#/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"

至少有两个问题:

  • 正如@hedder所建议的,该脚本在变量名中有一个输入错误
  • 应引用分配给变量的值
  • 打字错误

    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
    未设置或为空,ksh和bash中的
    ${varname:?[message]}
    构造将生成错误

    变量赋值

    像这样的任务

    varname=word1 long-string
    
    必须写为:

    varname="word long-string"
    
    否则,它将在为命令
    长字符串创建的环境中读取为赋值
    varname=word

    $ 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编程,请阅读手册页,特别是有关参数扩展和变量的部分。

    \usr/bin/ksh
    下面的一行添加
    set-u
    ,然后再次运行您的示例。shell将以
    -ksh:RomoteFile:parameter not set
    响应问题的关键在于,由于变量拼写错误,字符串“$newfile”为空。使用
    ksh-xscript
    运行脚本,查看每一行是如何执行的。我把它变成了一个wiki,因为前面有一个答案提到了变量赋值的问题。