File Test Operators का उपयोग
[[ -e path ]] # exists
[[ -f path ]] # regular file
[[ -d path ]] # directory
[[ -r path ]] # readable
Checking Existence
-e path true है अगर उस path पर बिल्कुल कुछ भी मौजूद हो (file, directory, symlink, आदि)। -f path इसे "मौजूद है और एक regular file है" तक narrow करता है।
उदाहरण: Checking Existence
#!/bin/bash
touch sample.txt
if [[ -e sample.txt ]]; then
echo "sample.txt exists"
fi
if [[ -f sample.txt ]]; then
echo "sample.txt is a regular file"
fi
rm -f sample.txt
Login to try C/C++/Java/PHP code in the editor
Checking Directories
-d path सिर्फ तब true है जब path मौजूद हो और एक directory हो। यह cd-ing करने से पहले या इसकी contents list करने से पहले standard guard है।
उदाहरण: Checking Directories
#!/bin/bash
mkdir -p sample_dir
if [[ -d sample_dir ]]; then
echo "sample_dir is a directory"
fi
if [[ ! -d does_not_exist ]]; then
echo "does_not_exist is not a directory"
fi
rmdir sample_dir
Login to try C/C++/Java/PHP code in the editor
Checking Permissions
-r, -w, और -x जांचते हैं कि current user के पास respectively एक path पर read, write, या execute permission है या नहीं। ये सिर्फ file के mode bits नहीं, असली OS-level permission checks reflect करते हैं।
उदाहरण: Checking Permissions
#!/bin/bash
touch perm_test.txt
chmod 644 perm_test.txt
if [[ -r perm_test.txt ]]; then
echo "readable"
fi
if [[ -w perm_test.txt ]]; then
echo "writable"
fi
if [[ ! -x perm_test.txt ]]; then
echo "not executable"
fi
rm -f perm_test.txt
Login to try C/C++/Java/PHP code in the editor
Checking File Size
-s path true है जब path मौजूद हो और इसका size zero bytes से ज़्यादा हो, जो उन्हें process करने से पहले empty files detect करने का एक quick तरीका है।
&& या [[ -f a && -r a ]] के साथ combine करें।उदाहरण: Checking File Size
#!/bin/bash
touch empty.txt
echo "has content" > full.txt
if [[ ! -s empty.txt ]]; then
echo "empty.txt is empty"
fi
if [[ -s full.txt ]]; then
echo "full.txt has content"
fi
rm -f empty.txt full.txt
Login to try C/C++/Java/PHP code in the editor
- "क्या यह path मौजूद है" check करने के लिए
-fउपयोग करना जब इसका असल में सिर्फ मतलब है "मौजूद है और एक regular file है"; एक directory-fमें fail होती है। [ -f $var ]के अंदर variable को quote करना भूल जाना, जो टूट जाता है अगर path में spaces हों या यह empty हो।- यह मान लेना कि
-wऔर-xहर edge case में current user की असली effective permissions perfectly reflect करते हैं (जैसे read-only filesystems), जब वे कभी-कभी misleading हो सकते हैं।
-eकिसी भी तरह की existence जांचता है;-fएक regular file जांचता है;-dएक directory जांचता है।-r,-w,-xcurrent user के लिए read, write, और execute permission जांचते हैं।-sजांचता है कि एक file मौजूद है और इसका size zero से ज़्यादा है।- Bash scripts में
[ ... ]के बजाय[[ ... ]]को prefer करें; यह unquoted variables और empty strings को ज़्यादा safely handle करता है।
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: