بررسی بودن یا نبودن فایل یا پوشه در شل اسکریپت

bash

در برخی اوقات ممکن است بخواهید وجود یک فایل یا پوشه را از طریق خط فرمان و یا شل اسکریپت بررسی کنید.برای اینکار می توان از دستور if به همراه اپراتورهای مربوطه این کار را انجام داد.

به عنوان نمونه می خواهیم بررسی کنیم که آیا فایل etc/hosts/ وجود دارد یا نه،برای اینکار می توان دستور پایین را اجرا کرد :

 

[ -f /etc/hosts ] && echo “Found” || echo “Not found”

 

در صورتی که فایل وجود داشته باشد Found نمایش داده خواهد شد و در عیر اینصورت Not found نمایش داده خواهد شد.

همین کار را نیز می توان به روش پایین و به صورت یک شل اسکریپت هم انجام داد :

 

#!/bin/bash
file=”/etc/hosts”
if [ -f “$file” ]
then
echo “$file found.”
else
echo “$file not found.”
fi

 

اپراتورهایی که می توان استفاده کرد به صورت زیر می باشند :

-b FILE
FILE exists and is block special

-c FILE
FILE exists and is character special

-d FILE
FILE exists and is a directory

-e FILE
FILE exists

-f FILE
FILE exists and is a regular file

-g FILE
FILE exists and is set-group-ID

-G FILE
FILE exists and is owned by the effective group ID

-h FILE
FILE exists and is a symbolic link (same as -L)

-k FILE
FILE exists and has its sticky bit set

-L FILE
FILE exists and is a symbolic link (same as -h)

-O FILE
FILE exists and is owned by the effective user ID

-p FILE
FILE exists and is a named pipe

-r FILE
FILE exists and read permission is granted

-s FILE
FILE exists and has a size greater than zero

-S FILE
FILE exists and is a socket

-t FD file descriptor FD is opened on a terminal

-u FILE
FILE exists and its set-user-ID bit is set

-w FILE
FILE exists and write permission is granted

-x FILE
FILE exists and execute (or search) permission is granted

 

بنابراین به صورت کلی می توان از این ساختار دستوری استفاده کرد :

 

 

if [ operator FileName ]
then
echo “FileName – Found, take some action here”
else
echo “FileName – Not found, take some action here”
fi

 

چنانچه قصد داشته باشید دستور شما فقط در یک خط نوشته شود می توان از نمونه ی پایین استفاده کنید :

 

file1=”/etc/hosts” ; if [ -f “$file1” ] ; then echo “$file1 found.” ; else echo “$file1 not found.” ; fi

 

امید است تا از این مطلب استفاده ی لازم را برده باشید.

ارسال یک پاسخ

آدرس ایمیل شما منتشر نخواهد شد.

This site uses Akismet to reduce spam. Learn how your comment data is processed.