2013-07-11 46 views
0

似乎什么是与此代码653-401不能重命名在shell脚本中使用的MV

#/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网站Information_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" 
+2

'“$ RomoteFile”'?? – shellter

+0

在'#/ usr/bin/ksh'下面的一行中添加'set -u'并重新运行你的例子。 shell会用'-ksh:RomoteFile:parameter not set'作出响应 –

+0

问题的关键是由于拼写错误的变量,字符串“$ newfile”是空的。用'ksh -x script'运行脚本来查看每行是如何执行的。 –

回答

0

,至少有两个问题:

  1. 脚本有变量名中一个错字,作为@shelter建议。
  2. 分配给变量的值应引用。

错字

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

的外壳是一个非常宽容的语言。错字很容易制作。

捕获它们的一种方法是强制未设置变量出现错误。 -u选项将做到这一点。在脚本的顶部包含set -u,或者使用ksh -u scriptname运行脚本。

另一种单独为每个变量测试此方法的方法,但它会为代码添加一些开销。如果变量varname没有设置或者是空

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

${varname:?[message]}构建体中的ksh和bash会产生错误。

变量赋值

varname=word1 long-string 

的分配必须被写为:

varname="word long-string" 

否则,它会读取作为命令创建环境分配varname=wordlong-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 

如果你是新来(科恩)shell编程,阅读手册页,尤其是参数扩展和变量部分。

+0

我把它变成了一个wiki,因为之前的答案提到了变量赋值的问题。 –