AMIT SHELKE AMIT SHELKE - 2 months ago 8
Bash Question

Check weather the path is directory or file in Shell script

I am trying to find out the array items are file path or directory path.

#!/bin/bash

declare -a arr=("/var/log/symantec/sgs-td","/var/lib/mysql/mysql-slow.log","/var/lib/mysql/mysql-error.log", "/var/log/sa")

## now loop through the above array
for i in "${arr[@]}"
do
if [[ -d $i ]]; then
echo "$i is a directory"
elif [[ -f $i ]]; then
echo "$i is a file"
else
echo "$i is not valid"
exit 1
fi
done


I am do not have knowledge of shell syntax.

If the path is directory then print ..is a directory or if file then print its a file.

Answer

The big small mistake was I put comma in array list while declaring. Rest Code has no problem and it works fine.

#!/bin/bash

declare -a arr=("/char/vlog/tec/sg" "/chr/lib/mysql/mysq.log" "/dar/lib/mysql/error.log" "/char/log/sua")

## now loop through the above array
for i in "${arr[@]}"
do
if [[ -d $i ]]; then
    echo "$i is a directory"
elif [[ -f $i ]]; then
    echo "$i is a file"
else
    echo "$i is not valid"
    exit 1
fi
done
Comments