Lego
Lego

Reputation: 191

Script to check if it is a directory or file and then process the rest of the script

I'm trying to rsync content on a specific directory to a different server and creating a script so that it is automated. My script will check if contents of the the directory has files or folders and in-turn move them using rsync. Below,

#!/bin/bash

for i in `ls /root/tags/` ; do
if [ -f "$i" ]
then
  echo "this is a file and I'll run a script if it is a file"
else
if [ -d "$i" ]
then
  echo "this is a dir and I'll run a script if it is a directory"
fi
fi
done

As you can see, my knowledge on shell scripts aren't anything to shout about but I'm trying to get this working.

Upvotes: 1

Views: 376

Answers (3)

hek2mgl
hek2mgl

Reputation: 158190

To get sure that files with spaces in their names don't cause problems, use something like this:

find . -maxdepth 1 -print0 | while read -d "" file ; do
    if [ -f "$file" ] ; then
        echo "$file is a file and I'll run a script if it is a file"
    elif [ -d "$file" ] ; then
        echo "$file is a dir and I'll run a script if it is a directory"
    fi
done

Upvotes: 0

bartimar
bartimar

Reputation: 3534

Another option is

cd /root/tags
for i in * ; do
  if [ -f "$i" ]; then
    echo "this is a file and I'll run a script if it is a file"
  elif [ -d "$i" ]; then
    echo "this is a dir and I'll run a script if it is a directory"
  fi
done

And that is the same as

path="/root/tags"
for i in "${path%/}"/* ; do
  if [ -f "$i" ]; then
    echo "this is a file and I'll run a script if it is a file"
  elif [ -d "$i" ]; then
    echo "this is a dir and I'll run a script if it is a directory"
  fi
done

Which I found like a good reusable code.

Upvotes: 3

vidit
vidit

Reputation: 6461

Your usage of else if is incorrect, it should be elif

if [ -f "$i" ]; then
  echo "this is a file and I'll run a script if it is a file"
elif [ -d "$i" ]; then
  echo "this is a dir and I'll run a script if it is a directory"
fi

Upvotes: 1

Related Questions