Reputation: 75
Problem Description:
i have a directory with a set of files and these files name saved in table into database called "File_names" i want to make shell script that loop on the directory and each time search if that file name exist in the database or not ,then if no : insert that name into database . else do nothing.
My trail:
FILES=/path/*
for f in $FILES
do
echo $f
done
But $f here contains the path + name i want to be the name only to do smthing like:
count = " select count(*) from File_names where name = $f"
How can i do this ?
Thanks in Advance
Upvotes: 0
Views: 1122
Reputation: 107799
I don't find your question very clear; I'll answer the shell part of it as I understand it.
As far as I understand, you want to run a command on each file in a directory. But you're only interested in the base name of the file, i.e., without the directory part.
Alternative 1
for f in /path/*; do
echo "$(basename "$f")"
done
Alternative 2
set -e
cd /path
for f in *; do
echo "$f"
done
set -e
is so that the script stops if the cd
command fails. It's usually a good idea to start shell scripts with set -e
.
Be careful about quoting, in case the file names contain punctuation characters or spacing. This applies to both the shell part and the SQL part: the way you're constructing the query in your question is completely open to SQL injection (think what would happen if someone created a file called foo; DROP TABLE File_names
).
Upvotes: 2