In this article, we will see how to user IF statements and conditional expressions to check if a file exist or folder exist to perform execution depend on result in bash shell script in Linux.
In bash shell, when we need to check a condition to execute particular code block, IF and IF else statements can be used. It eveluates It evaluates an expression to decide whether to perform a code. "-e" means if file exist, "-d" means if folder exist. With using those, we can check if filename we send as parameter exists or folder exists. Depend on result, we can further perform a create folder or file operation.
Lets look to its syntax.
if [ -e $filename ]; then
echo "a file with that name exists"
else
echo "a file with that name does not exists"
fi
if [ -d $dir ]; then
echo "a directory with that name exists"
else
echo "a directory with that name does not exists"
fi
Lets see it in bash shell scripting example.
As above output indicates, we added a basic IF statement to a shell bash script with name "1.sh". Our script takes 2 parameter from shell call. First parameter is folder name, second parameter is file name. We assign those to parameters in our script, and perform if given parameters exist as file name and folder name. As we sen "1.sh" as parameter to our script, since its script also checkts itself, it returns exist.