Sprawdź, czy katalog istnieje w skrypcie powłoki

Jakie polecenie może być użyte do sprawdzenia czy katalog istnieje czy nie, w skrypcie powłoki?

Author: Jahid, 2008-09-13

30 answers

Aby sprawdzić, czy katalog istnieje w skrypcie powłoki, możesz użyć następującego polecenia:

if [ -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY exists.
fi

Lub sprawdzić, czy katalog nie istnieje:

if [ ! -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY doesn't exist.
fi

Jednakże, jak zauważa Jon Ericson , kolejne polecenia mogą nie działać zgodnie z przeznaczeniem, jeśli nie weźmiesz pod uwagę, że dowiązanie symboliczne do katalogu również przejdzie tę kontrolę. Np. uruchamianie tego:

ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then 
  rmdir "$SYMLINK" 
fi

Wyświetli komunikat o błędzie:

rmdir: failed to remove `symlink': Not a directory

Więc dowiązania symboliczne mogą być traktowane inaczej, jeśli kolejne polecenia oczekują katalogów:

if [ -d "$LINK_OR_DIR" ]; then 
  if [ -L "$LINK_OR_DIR" ]; then
    # It is a symlink!
    # Symbolic link specific commands go here.
    rm "$LINK_OR_DIR"
  else
    # It's a directory!
    # Directory command goes here.
    rmdir "$LINK_OR_DIR"
  fi
fi

Zwróć szczególną uwagę na podwójne cudzysłowy używane do zawijania zmiennych, powód tego jest wyjaśniony przez 8jean w innej odpowiedzi .

Jeśli zmienne zawierają spacje lub inne nietypowe znaki, prawdopodobnie spowoduje to niepowodzenie skryptu.

 4272
Author: Grundlefleck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-20 11:23:27

Pamiętaj, aby zawsze zawijać zmienne w podwójne cudzysłowy, gdy odwołujesz się do nich w skrypt bash. Dzieci w dzisiejszych czasach dorastają z myślą, że mogą mieć spacje i wiele innych zabawnych postaci w nazwach katalogów. (Spacje! Za moich czasów nie mieliśmy żadnych fantazyjnych miejsc! ;))

Pewnego dnia jedno z tych dzieci uruchomi Twój skrypt z $DIRECTORY ustawionym na "My M0viez" i twój skrypt wybuchnie. Nie chcesz tego. Więc użyj tego.
if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists, even if it contains spaces
fi
 464
Author: 8jean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-11 07:08:53

Uwaga test - d może dać zaskakujące wyniki:

$ ln -s tmp/ t
$ if [ -d t ]; then rmdir t; fi
rmdir: directory "t": Path component not a directory

Plik W: "kiedy katalog nie jest katalogiem?"Odpowiedź:" gdy jest to dowiązanie symboliczne do katalogu."Nieco dokładniejszy test:

if [ -d t ]; then 
   if [ -L t ]; then 
      rm t
   else 
      rmdir t
   fi
fi

Więcej informacji można znaleźć w podręczniku Bash na temat wyrażeń warunkowych Bash oraz [ wbudowane polecenie oraz [[ compound commmand .

 208
Author: Jon Ericson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-11 14:10:31

Uważam, że wersjadouble-bracket sprawia, że pisanie testów logicznych jest bardziej naturalne:

if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
    echo "It's a bona-fide directory"
fi
 200
Author: yukondude,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-01 01:56:50

Forma krótsza:

[ -d "$DIR" ] && echo "Yes"
 130
Author: elmarco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-25 13:13:44

Aby sprawdzić, czy katalog istnieje, możesz użyć prostej struktury if takiej jak Ta:

if [ -d directory/path to a directory ] ; then
#Things to do

else #if needed #also: elif [new condition] 
# things to do
fi

Możesz to zrobić również w negatywie

if [ ! -d directory/path to a directory ] ; then
# things to do when not an existing directory

Uwaga : należy zachować ostrożność, pozostawić puste miejsca po obu stronach obu otwieranych i zamykanych aparatów ortodontycznych.

Z tą samą składnią można użyć:

-e: any kind of archive 

-f: file 

-h: symbolic link 

-r: readable file 

-w: writable file 

-x: executable file 

-s: file size greater than zero 
 119
Author: Jorge Barroso,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-23 22:28:05
if [ -d "$DIRECTORY" ]; then  
    # Here if $DIRECTORY exists  
fi
 94
Author: Ayyappa Boligala,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-01 01:01:00

Możesz użyć test -d (patrz man test).

-d file True Jeśli plik istnieje i jest katalogiem.

Na przykład:

test -d "/etc" && echo Exists || echo Does not exist

Uwaga: polecenie test jest takie samo jak wyrażenie warunkowe [ (Zobacz: man [), więc jest przenośne w skryptach powłoki.

[ - jest to synonim test wbudowanego, ale ostatni argument musi być literalny ], aby dopasować otwarcie [.

Dla możliwych opcji lub dalszej pomocy, sprawdzić:

  • help [
  • help test
  • man test lub man [
 77
Author: kenorb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-16 17:01:20

Albo za coś zupełnie bezużytecznego:

[ -d . ] || echo "No"
 54
Author: sth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-17 15:47:53

Oto bardzo pragmatyczny idiom:

(cd $dir) || return # is this a directory,
                    # and do we have access?

Zazwyczaj zawijam go w funkcję:

can_use_as_dir() { 
    (cd ${1:?pathname expected}) || return
}

Lub:

assert_dir_access() { 
    (cd ${1:?pathname expected}) || exit
}

Fajną rzeczą w tym podejściu jest to, że nie muszę myśleć o dobrym komunikacie o błędzie.

cd da mi już standardową, jednowierszową wiadomość na stderr. To również da więcej informacji, niż będę w stanie dostarczyć. Wykonując cd wewnątrz subshell ( ... ), polecenie nie wpływa na bieżący katalog wywołującego. Jeśli katalog istnieje, ta podshell i funkcja są po prostu no-op.

Następny jest argument, który przekazujemy do cd: ${1:?pathname expected}. Jest to bardziej rozbudowana forma substytucji parametrów, która jest wyjaśniona bardziej szczegółowo poniżej.

TL; dr: jeśli łańcuch przekazywany do tej funkcji jest pusty, ponownie wychodzimy z podshell ( ... ) i wracamy z funkcji z podanym Komunikatem o błędzie.


Cytowanie ze strony man ksh93:

${parameter:?word}

Jeśli parameter jest ustawione i jest non-null, a następnie zastępuje jego wartość; w przeciwnym razie, print word i wyjście z powłoki (jeśli nie interaktywne). Jeśli word jest pominięte, drukowana jest standardowa wiadomość.

I

Jeśli dwukropek {[14] } zostanie pominięty w powyższych wyrażeniach, to shell sprawdza tylko, czy parametr jest ustawiony, czy nie.

Frazowanie tutaj jest specyficzne dla dokumentacji powłoki, ponieważ word może odnosić się do wszelkich rozsądnych ciągów, w tym whitespace.

W tym konkretnym przypadku wiem, że standardowy komunikat o błędzie 1: parameter not set nie jest wystarczający, więc przybliżam typ wartości, której tutaj oczekujemy - pathname katalogu.

Uwaga filozoficzna: Powłoka nie jest językiem zorientowanym obiektowo, więc wiadomość mówi pathname, a nie directory. Na tym poziomie wolałbym, żeby było to proste - argumenty funkcji to tylko ciągi znaków.

 46
Author: Henk Langeveld,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-16 12:00:18
if [ -d "$Directory" -a -w "$Directory" ]
then
    #Statements
fi

Powyższy kod sprawdza, czy katalog istnieje i czy można go zapisać.

 35
Author: muralikrishna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-25 08:51:12
  1. Prosty skrypt do sprawdzenia czy katalog lub plik jest obecny czy nie:

    if [ -d /home/ram/dir ]   # for file "if [-f /home/rama/file]" 
    then 
        echo "dir present"
    else
        echo "dir not present"
    fi
    
  2. Prosty skrypt sprawdzający czy katalog jest obecny czy nie:

    mkdir tempdir   # if you want to check file use touch instead of mkdir
    ret=$?
    if [ "$ret" == "0" ]
    then
        echo "dir present"
    else
        echo "dir not present"
    fi
    

    Powyższe Skrypty sprawdzą czy katalog jest obecny czy nie

    $? jeśli ostatnie polecenie zakończy się sukcesem, zwraca "0", w przeciwnym razie wartość niezerowa. Załóżmy, że tempdir jest już obecne, wtedy mkdir tempdir Da błąd jak poniżej:

    Mkdir: nie można utworzyć katalogu 'tempdir': plik istnieje

 28
Author: siva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-18 15:18:44

Wpisz ten kod na bash promt

if [ -d "$DIRECTORY" ]; then
  # if true this block of code will execute
fi
 24
Author: santosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-05 03:39:01

Więcej funkcji za pomocą find

  • Sprawdź istnienie folderu w podkatalogach:

    found=`find -type d -name "myDirectory"`
    if [ -n "$found"]
    then
        # The variable 'found' contains the full path where "myDirectory" is.
        # It may contain several lines if there are several folders named "myDirectory".
    fi
    
  • Sprawdzenie istnienia jednego lub kilku folderów na podstawie wzorca w bieżącym katalogu:

    found=`find -maxdepth 1 -type d -name "my*"`
    if [ -n "$found"]
    then
        # The variable 'found' contains the full path where folders "my*" have been found.
    fi
    
  • Obie kombinacje. W poniższym przykładzie sprawdza istnienie folderu w bieżącym katalogu:

    found=`find -maxdepth 1 -type d -name "myDirectory"`
    if [ -n "$found"]
    then
        # The variable 'found' is not empty => "myDirectory"` exists.
    fi
    
 20
Author: Neil Neyman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-10 10:49:39

W rzeczywistości, powinieneś użyć kilku narzędzi, aby uzyskać kuloodporne podejście:]}

DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
if [[ -d "${DIR_PATH}" ]] ; Then # now you're testing
    echo "It's a dir";
fi

Nie musisz się martwić o spacje i znaki specjalne, dopóki używasz "${}".

Zauważ, że [[]] nie jest tak przenośny jak [], ale ponieważ większość ludzi pracuje z nowoczesnymi wersjami Basha (ponieważ przecież większość ludzi nawet nie pracuje z wierszem poleceń :-p), korzyść jest większa niż kłopot.

 19
Author: e-satis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-22 08:33:54

Aby sprawdzić więcej niż jeden katalog użyj tego kodu:

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
fi
 16
Author: Raamesh Keerthi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-27 13:02:41

Czy rozważałeś po prostu robienie tego, co chcesz robić w if, zamiast patrzeć, zanim skoczysz?

IE, jeśli chcesz sprawdzić istnienie katalogu przed jego wejściem, spróbuj po prostu zrobić to:

if pushd /path/you/want/to/enter; then
    # commands you want to run in this directory
    popd
fi

Jeśli ścieżka, którą podałeś pushd istnieje, wejdziesz do niej i wyjdzie z 0, co oznacza, że część then instrukcji zostanie wykonana. Jeśli nie istnieje, nic się nie stanie (poza jakimś wyjściem mówiącym, że katalog nie istnieje, co jest prawdopodobnie pomocny efekt uboczny w debugowaniu).

Wydaje się lepsze niż to, co wymaga powtarzania się:

if [ -d /path/you/want/to/enter ]; then
    pushd /path/you/want/to/enter
    # commands you want to run in this directory
    popd
fi

To samo działa z cd, mv, rm, itd... jeśli wypróbujesz je na plikach, które nie istnieją, zakończą one działanie z błędem i wydrukują komunikat, że nie istnieją, a twój then blok zostanie pominięty. Jeśli wypróbujesz je na istniejących plikach, polecenie wykona i zakończy działanie ze statusem 0, pozwalając na wykonanie then bloku.

 15
Author: ArtOfWarfare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-07 16:24:23
[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"

Uwaga: cytowanie zmiennych jest dobrą praktyką.

 14
Author: Jahid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-20 04:20:51

Sprawdź czy katalog istnieje, w przeciwnym razie Utwórz jeden

[ -d "$DIRECTORY" ] || mkdir $DIRECTORY
 14
Author: David Okwii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-23 07:25:55
[ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"
 12
Author: Juan Carlos Kuri Pinto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-28 08:36:06

Ta odpowiedź zawinięta jako skrypt powłoki

Przykłady

$ is_dir ~                           
YES

$ is_dir /tmp                        
YES

$ is_dir ~/bin                       
YES

$ mkdir '/tmp/test me'

$ is_dir '/tmp/test me'
YES

$ is_dir /asdf/asdf                  
NO

# Example of calling it in another script
DIR=~/mydata
if [ $(is_dir $DIR) == "NO" ]
then
  echo "Folder doesnt exist: $DIR";
  exit;
fi

Is_dir

function show_help()
{
  IT=$(CAT <<EOF

  usage: DIR
  output: YES or NO, depending on whether or not the directory exists.

  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

DIR=$1
if [ -d $DIR ]; then 
   echo "YES";
   exit;
fi
echo "NO";
 11
Author: Brad Parks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:36

Użycie opcji -e spowoduje sprawdzenie plików i dotyczy to również katalogów.

if [ -e ${FILE_PATH_AND_NAME} ]
then
    echo "The file or directory exists."
fi
 9
Author: bailey86,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-28 08:34:29

Według Jonathan komentarz:

Jeśli chcesz utworzyć katalog, który jeszcze nie istnieje, najprostszą techniką jest użycie mkdir -p, która tworzy katalog - i wszelkie brakujące katalogi w ścieżce-i nie zawodzi, jeśli katalog już istnieje, więc możesz to zrobić wszystko na raz za pomocą:

mkdir -p /some/directory/you/want/to/exist || exit 1
 8
Author: kenorb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:37
if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists
fi
To nie jest do końca prawda... Jeśli chcesz przejść do tego katalogu, musisz również mieć prawa wykonywania w tym katalogu. Może ty też musisz mieć prawa do zapisu.

Therfore:

if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then
    # ... to go to that directory (even if DIRECTORY is a link)
    cd $DIRECTORY
    pwd
fi

if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then
    # ... to go to that directory and write something there (even if DIRECTORY is a link)
    cd $DIRECTORY
    touch foobar
fi
 7
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-18 10:52:57

Polecenie ls w połączeniu z opcją -l (long listing) zwraca atrybuty informacji o plikach i katalogach.
W szczególności pierwszym znakiem wyjścia ls -l jest zwykle d lub - (dash). W przypadku d ten wymieniony na pewno jest katalogiem.

Następujące polecenie w jednej linii powie Ci, czy dany ISDIR zmienna zawiera ścieżkę do katalogu lub nie:

[[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
    echo "YES, $ISDIR is a directory." || 
    echo "Sorry, $ISDIR is not a directory"

Praktyczne zastosowanie:

    [claudio@nowhere ~]$ ISDIR="$HOME/Music" 
    [claudio@nowhere ~]$ ls -ld "$ISDIR"
    drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." ||
        echo "Sorry, $ISDIR is not a directory"
    YES, /home/claudio/Music is a directory.

    [claudio@nowhere ~]$ touch "empty file.txt"
    [claudio@nowhere ~]$ ISDIR="$HOME/empty file.txt" 
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." || 
        echo "Sorry, $ISDIR is not a directoy"
    Sorry, /home/claudio/empty file.txt is not a directory
 6
Author: ztank1013,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-26 11:21:39
file="foo" 
if [[ -e "$file" ]]; then echo "File Exists"; fi;
 5
Author: ajmartin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-22 02:39:07

Jeśli chcesz sprawdzić, czy katalog istnieje, niezależnie od tego, czy jest to prawdziwy katalog czy dowiązanie symboliczne, użyj tego:

ls $DIR
if [ $? != 0 ]; then
        echo "Directory $DIR already exists!"
        exit 1;
fi
echo "Directory $DIR does not exist..."

Wyjaśnienie: polecenie " ls "wyświetla błąd" ls: / x: No such file or directory "jeśli katalog lub dowiązanie symboliczne nie istnieje, a także ustawia kod powrotu, który można pobrać poprzez"$?", do non-null (normalnie "1"). Upewnij się, że sprawdzasz kod zwrotu bezpośrednio po wywołaniu "ls".

 5
Author: derFunk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-08 10:38:41

(1)

[ -d Piyush_Drv1 ] && echo ""Exists"" || echo "Not Exists"

(2)

[ `find . -type d -name Piyush_Drv1 -print | wc -l` -eq 1 ] && echo Exists || echo "Not Exists"

(3)

[[ -d run_dir  && ! -L run_dir ]] && echo Exists || echo "Not Exists"

Jeśli znaleziono problem z jednym z powyższych podejść.

Z poleceniem ls; przypadki, gdy katalog nie istnieje-wyświetlany jest komunikat o błędzie

$ [[ ls -ld SAMPLE_DIR| grep ^d | wc -l -eq 1 ]] & & echo exists / / not exists -ksh: not: not found [brak takiego pliku lub katalogu]

 5
Author: Piyush Baijal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-13 07:38:37

Świetne rozwiązania, ale ostatecznie każdy skrypt zawiedzie, jeśli nie jesteś w odpowiednim katalogu. Więc kod taki:

if [ -d "$LINK_OR_DIR" ]; then 
if [ -L "$LINK_OR_DIR" ]; then
    # It is a symlink!
    # Symbolic link specific commands go here
    rm "$LINK_OR_DIR"
else
    # It's a directory!
    # Directory command goes here
    rmdir "$LINK_OR_DIR"
fi
fi

Zakończy się pomyślnie tylko wtedy, gdy w momencie wykonania znajdujesz się w katalogu z podkatalogiem, którego szukasz.

Rozumiem początkowe pytanie takie jak: aby sprawdzić, czy katalog istnieje niezależnie od pozycji użytkownika w systemie plików. Więc użycie polecenia "find" może trick:

dir=" "
echo "Input directory name to search for:"
read dir
find $HOME -name $dir -type d

To rozwiązanie jest dobre, ponieważ pozwala na użycie symboli wieloznacznych, przydatnej funkcji podczas wyszukiwania plików / katalogów. Jedyny problem polega na tym, że jeśli wyszukiwany katalog nie istnieje, polecenie 'find' nie wyświetli niczego na stdout (nie jest to eleganckie rozwiązanie jak na mój gust) i będzie miało zerowe wyjście. Może ktoś mógłby to poprawić.

 4
Author: dromichaetes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-12 21:46:29

Poniżej można znaleźć,

find . -type d -name dirname -prune -print
 4
Author: Sadhun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-13 13:41:35