2012-11-21 42 views
0

每次運行此代碼時,都會收到錯誤文件或目錄不存在。爲什麼?Linux文件刪除錯誤

read -p "Enter the filename/path of the file you wish to delete : " filename 
echo "Do you want to delete this file" 
echo "Y/N" 
read ans 
case "$ans" in 
    Y) "`readlink -f $filename`" >>~/TAM/store & mv $filename ~/TAM/dustbin 
     echo "File moved" ;; 
    N) "File Not deleted" ;; 
esac 

當我輸入文件名/目錄恰好和三重檢查它的右我仍然得到這個錯誤,但部分的readlink作品。

+0

是什麼'設置-x'透露? – pilcrow

+0

我確實發現它不起作用,但是/ root/TAM/filename的作品 – TAM

+0

你確定這個腳本沒有遺漏嗎? '「...」>> ...'不是一個有效的構造,除非你計劃執行你正在嘗試移動的文件... – thkala

回答

2

複述/彙總/擴展my answer for a similar question

  • 我懷疑你的真正用意在腳本中使用&而不是&&

  • "File Not deleted"不是在我使用的任何Linux系統上的有效命令。也許你錯過了echo那裏?

  • 您必須修復您的變量報價。如果filename變量包含空白,則$filename由shell擴展爲多個參數。你需要把它括入雙引號:

    mv "$filename" ~/TAM/dustbin 
    
  • 我沒有看到你的腳本的任何地方創建~/TAM/目錄...

1

你缺少一個echo和一個&&

  1. 使用echo "`command`"來管理結果字符串的命令。或者,您可以直接使用command而不用反引號和引號(不會將結果存儲在字符串中),在這種情況下,您不需要echo,因爲該命令會將其結果傳遞給下一個命令。
  2. 單個&將在後臺運行上述命令(async。)。要檢查返回值並有條件執行,您需要&&||

這是一個完整的解決方案/例子(包括一些記錄。):

# modified example not messing the $HOME dir. 
# should be save to run in a separate dir 
touch testfile     #create file for testing 
read -p "Enter the filename/path of the file you wish to delete : " filename 
echo "Do you want to delete this file: $filename" 
echo "Y/N" 
read ans 
touch movedfiles    #create a file to store the moved files 
[ -d _trash ] || mkdir _trash #create a dustbin if not already there 
case "$ans" in 
    Y) readlink -f "$filename" >> movedfiles && echo "File name stored" && 
     mv "$filename" _trash && echo "File moved" ;; 
    N) echo "File Not deleted" ;; 
esac 
cat movedfiles     #display all moved files 
+0

使用'readlink -f「$ filename >> >>〜/ TAM/store'(使用問題中的名稱;您使用'movedfiles')會更簡單。 '&&'後面的反斜槓不需要;這不是你正在編程的海洋。 –

+0

Thx,我不知道'&&'不需要在行末加反斜槓。 – Juve