filmov
tv
Shell Scripting: Mastering File Test Operators with Real-Time Examples

Показать описание
File operators (also called file test operators) are special symbols or expressions used in shell scripts to check properties or conditions of files and directories.
They help scripts make decisions based on file attributes like:
• Does a file exist?
• Is it a directory?
• Is it readable or writable?
• Is it empty?
Types of File Operators:
Operator Meaning Example
-d Directory [ -d myfolder ]
-L File is a symbolic link [ -L shortcut ]
EX1:
#!/bin/bash
# 1. Check if file exists
if [[ -e "$file" ]]; then
echo "$file exists."
# 2. Is it a regular file?
if [[ -f "$file" ]]; then
echo "$file is a regular file."
fi
# 3. Is it a directory?
if [[ -d "$file" ]]; then
echo "$file is a directory."
fi
# 4. Is it readable?
if [[ -r "$file" ]]; then
echo "$file is readable."
fi
# 5. Is it writable?
if [[ -w "$file" ]]; then
echo "$file is writable."
fi
# 6. Is it executable?
if [[ -x "$file" ]]; then
echo "$file is executable."
fi
# 7. Is it non-empty?
if [[ -s "$file" ]]; then
echo "$file is not empty."
else
echo "$file is empty."
fi
# 8. Is it a symbolic link?
if [[ -L "$file" ]]; then
echo "$file is a symbolic link."
fi
else
echo "$file does not exist."
fi
They help scripts make decisions based on file attributes like:
• Does a file exist?
• Is it a directory?
• Is it readable or writable?
• Is it empty?
Types of File Operators:
Operator Meaning Example
-d Directory [ -d myfolder ]
-L File is a symbolic link [ -L shortcut ]
EX1:
#!/bin/bash
# 1. Check if file exists
if [[ -e "$file" ]]; then
echo "$file exists."
# 2. Is it a regular file?
if [[ -f "$file" ]]; then
echo "$file is a regular file."
fi
# 3. Is it a directory?
if [[ -d "$file" ]]; then
echo "$file is a directory."
fi
# 4. Is it readable?
if [[ -r "$file" ]]; then
echo "$file is readable."
fi
# 5. Is it writable?
if [[ -w "$file" ]]; then
echo "$file is writable."
fi
# 6. Is it executable?
if [[ -x "$file" ]]; then
echo "$file is executable."
fi
# 7. Is it non-empty?
if [[ -s "$file" ]]; then
echo "$file is not empty."
else
echo "$file is empty."
fi
# 8. Is it a symbolic link?
if [[ -L "$file" ]]; then
echo "$file is a symbolic link."
fi
else
echo "$file does not exist."
fi