2013-07-11 45 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,因爲之前的答案提到了變量賦值的問題。 –