2012-11-11 118 views
0

當條目存在時,我的條件可以正常工作,但如果它們沒有,它似乎同時執行thenelse語句(這是正確的術語?)。爲什麼這個條件返回「沒有這樣的文件或目錄」

script.sh

#!/bin/bash 
if [[ $(find path/to/dir/*[^thisdir] -type d -maxdepth 0) ]] 
    then 
    find path/to/dir/*[^thisdir] -type d -maxdepth 0 -exec mv {} new/location \; 
    echo "Huzzah!" 
    else 
    echo "hey hey hey" 
fi 

提示
對於第一呼叫時,顯示目錄在那裏;在第二個,他們已經從第一個電話轉移。

$ sh script.sh 
Huzzah! 
$ sh script.sh 
find: path/to/dir/*[^thisdir]: No such file or directory 
hey hey hey 

我該如何解決這個問題?

試圖建議(S)

if [[ -d $(path/to/dir/*[^thisdir]) ]] 
    then 
    find path/to/dir/*[^thisdir] -type d -maxdepth 0 -exec mv {} statamic-1.3-personal/admin/themes \; 
    echo "Huzzah!" 
    else 
    echo "hey hey hey" 
fi 

結果

$ sh script.sh 
script.sh: line 1: path/to/dir/one_of_the_dirs_to_be_moved: is a directory 
hey hey hey 
+0

你試過的建議*已經接近正確,但需要保留'$()',並且必須達到'... dir /!(thisdir)'而不是'* [^ thisdr]'。但是,只有當path/to/dir/* [^ thisdir]完全匹配** 1 **條目時,這纔會起作用。看看我的答案... –

回答

1

你的錯誤是在if [[ $(find path/to/dir/*[^thisdir] -type d -maxdepth 0) ]]可能發生的,然後它去到別的,因爲發現的錯誤了。

find希望其目錄參數存在。根據你正在嘗試做你應該考慮

$(find path/to/dir/ -name "appropriate name pattern" -type d -maxdepth 1) 

而且,我會考慮在if使用實際的邏輯功能。有關文件條件,請參閱this

+0

你的第一個建議沒有奏效。與以前相同的結果。第二個(if中的邏輯函數)是有意義的,但是我必須做一些錯誤的事情。我會用該信息更新問題。帶-d選項的 – curtisblackwell

+0

你不需要$()。你基本上試圖執行每個目錄。應該是'[[-d path/to/dir/whatever''。但是,我從來沒有使用* [^ thisdir]模式。你想要做什麼? –

+0

最終使用'find path/to/dir/* \! -name'this_dir_stays_put'-type d -maxdepth 0 -exec mv {} new/location \;'這篇文章的目的不是爲了解決我的問題,而是爲了理解爲什麼這不能解決我的問題。亞歷克斯是對的,錯誤在於我在條件中找到了什麼。 – curtisblackwell

2

似乎有一些錯誤:

首先,模式path/to/dir/*[^thisdir]在bash中的解釋方式與path/to/dir/*[^dihstr]的意思相同*所有文件名結尾爲d,i,h, s,tr

比,如果你在尋找的東西,這目錄(path/to/dir),但不是在path/to/dir/thisdir而不是在第n個子目錄,你可以bannish find寫:

編輯:有我的樣品也出現錯誤:[ -e $var ]是錯誤的。

declare -a files=(path/to/dir/!(thisdir)) 
if [ -e $files ] ;then 
    mv -t newlocation "${files[@]}" 
    echo "Huzzah!" 
else 
    echo "hey hey hey" 
fi 

如果您需要find在subirs搜索,請給我們的樣品和/或更多的描述。

+0

+1更好更清潔的解決方案。 – dimir

0

該OP希望將除thisdir之外的所有文件移動到新的位置。

使用find的溶液將是',而不是使用bash小號功能的外殼膨脹,以排除使用findthisdir

#!/bin/bash 
if [[ $(find path/to/directory/* -maxdepth 0 -type d -not -name 'thisdir') ]] 
    then 
     find path/to/directory/* -maxdepth 0 -type d -not -name 'thisdir' -exec mv {} new/location \; 
     echo "Huzzah!" 
    else 
     echo "hey hey hey" 
fi 

這已經過測試,並在4.2.39 bash版本的作品,和GNU findutils v4.5.10。

相關問題