Jak mogę sprawdzić, czy katalog istnieje w skrypcie powłoki Bash?

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

Author: Peter Mortensen, 2008-09-12

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.

 5343
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
2020-05-07 11:54:34

Pamiętaj, aby zawsze zawijać zmienne w podwójne cudzysłowy podczas odwoływania się do nich w skrypcie 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
 554
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
2020-05-07 11:56:37

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 .

 239
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
 224
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:

# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"
 170
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
2021-02-02 10:21:27

Aby sprawdzić, czy katalog istnieje, możesz użyć prostej if struktury 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żna to również zrobić w negatywie:

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

Uwaga : Bądź ostrożny. Pozostawić puste miejsca po obu stronach obu otwieranych i zamykanych szelek.

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
 137
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
2020-05-07 12:12:00
  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 jest pomyślne, zwraca "0", w przeciwnym razie wartość niezerowa. Załóżmy, że tempdir jest już obecny. Następnie mkdir tempdir wyświetli błąd jak poniżej:

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

 128
Author: yoctotutor.com,
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
2020-09-09 10:30:04

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 [
 95
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"
 57
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ą wiadomość z jedną linią do standardowego błędu . 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 dzwoniący. 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 nie jest null, to zastąp 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 jest charakterystyczne dla dokumentacji powłoki, ponieważ {[12] } może odnosić się do dowolnego rozsądnego ciągu znaków, włącznie z białymi spacjami.

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.

 56
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
2020-05-07 12:07:07
if [ -d "$Directory" -a -w "$Directory" ]
then
    #Statements
fi

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

 37
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
DIRECTORY=/tmp

if [ -d "$DIRECTORY" ]; then
    echo "Exists"
fi

Wypróbuj online

 28
Author: Vishal,
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
2019-10-09 06:08:03

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
    
 26
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
2020-12-17 13:12:15

Wpisz ten kod w wierszu polecenia Bash:

if [ -d "$DIRECTORY" ]; then
    # If true this block of code will execute
fi
 25
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
2020-05-07 12:10:49

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 ma potrzeby martwić się 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.

 21
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
2020-05-07 11:58:04

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

Tzn. 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 pomocnym efektem ubocznym w debugowaniu).

Wydaje się lepiej 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, Komenda uruchomi się i zakończy ze statusem 0, pozwalając blokowi then na wykonać.

 18
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
2020-05-12 06:04:12
[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"

Uwaga: cytowanie zmiennych jest dobrą praktyką.

Explanation:

  • -d: Sprawdź czy jest to katalog
  • -L: sprawdź czy jest to dowiązanie symboliczne
 17
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
2020-05-07 13:29:06

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

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
fi
 15
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

Sprawdź czy katalog istnieje, w przeciwnym razie zrób jeden:

[ -d "$DIRECTORY" ] || mkdir $DIRECTORY
 15
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
2020-05-07 12:20:38
[ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"
 13
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
 10
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
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.

Dlatego:

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
 8
Author: Peter Mortensen,
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
2020-05-07 12:00:32

Zgodnie z komentarzem Jonathana :

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
2020-05-07 12:19:51

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

Użyj programu file. Biorąc pod uwagę, że wszystkie katalogi są również plikami w Linuksie, wystarczy wydać następujące polecenie:

file $directory_name

Sprawdzanie nieistniejącego pliku: file blah

Wyjście: cannot open 'blah' (No such file or directory)

Sprawdzanie istniejącego katalogu: file bluh

Wyjście: bluh: directory

 6
Author: Sudip Bhandari,
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
2020-05-12 06:08:28
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

Istnieją ś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. Jedynym problemem jest to, że jeśli szukany katalog nie istnieje, polecenie 'find' nie wyświetli niczego na standardowe wyjście (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ć.

 5
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
2020-05-07 12:03:24

Poniżej find można użyć,

find . -type d -name dirname -prune -print
 5
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
2020-05-07 12:09:12

(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 zostanie znaleziony problem z jednym z powyższych podejść:

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 [No such file or directory]

 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
2020-05-07 12:17:04