Tuesday, January 31, 2012

Expression Example

Here are some common expression which can use with if condition

Check Directory
-d file >> True if file is a directory
#!/bin/bash
if [ -d /home ]; then
echo "/home is directory"
else
echo "/home is not directory"
fi
=================================================================
Check the file is exists
-e file >>True if file exists.
#!/bin/bash 
if [ -e /home/admin/.bash_profile ]; 
then 
echo ".bash_profile exists" 
else 
echo ".bash_profile not exists" 
fi
==================================================================
Check the file is regular file
-f file >>True if file exists and is a regular file
#!/bin/bash 
if [ -f /etc/passwd ]; then  
echo "/etc/passwd file is regular file" 
else 
echo " /etc/passwd file is not regular file "
fi
-------------------------------------------------------------------------------------------------
#!/bin/bash 
if [ -f /dev/fd0 ] then 
echo "regular file" 
else 
echo "not regular file" 
fi
===================================================================
Check the file has symbolic link
-L file >>  True if file is a symbolic link

#!/bin/bash 
if [ -L /dev/cdrom ] then 
echo "symbolink link file" 
else 
echo "not symbolink link file" 
fi
===================================================================
Check read, write execute permission
-r file >> True file is readable
-w file >> True file is writeable
-x file >> True file is executable

#!/bin/bash 
if [ -r /etc/passwd ] then 
echo "file is readable" 
else 
echo "file is not readable" 
fi

====================================================================
Check new or old file
file1 -nt file2 >> True  file1 newer than file2
file1 -ot file2 >> True  file1 older than file2

#!/bin/bash 
if [ /home/admin/test1 -nt /home/admin/test2] then 
echo "file test1 is new" 
else 
echo "file test2 is new" 
fi
=====================================================================

No comments:

Post a Comment