Drumitar
Drumitar

Reputation: 11

Simple bash script to determine if a file is in a directory

I'm trying to figure out in bash how to simply show that an argument which is a file is in another argument which is a directory, and then remove the file if it is. I was thinking about setting a variable to $(dirname $file) and then comparing it to the directory name, but I'm not sure if that is the right direction to go in for this question. or would I do a ls of the directory and somehow match that to the file?

Upvotes: 0

Views: 4630

Answers (4)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

As stated, the question is slightly ambiguous. It isn't entirely clear (to me) which file of the two should be deleted. On further pondering, I think that if the file exists in the remote directory, the file name as specified should be deleted. That leads to this script, I believe:

filename="$1"
dirname="$2"
basename=$(basename "$filename")
pathname="$dirname/$filename"
if [ -f "$pathname" ]
then rm -f "$filename"
fi

You could test for "$dirname" being a directory; however, if it is not a directory, then the pathname based on it won't be a file (so the test for it being a file will fail), so the test on the directory is superfluous unless you want informative error reporting.

Note that the script shown will work in the presence of blanks in the file or directory names. Miss any of the quotes and it would not work properly.

Upvotes: 1

ajreal
ajreal

Reputation: 47311

You can make use of if and test :-

file="somedir/somefile.txt"
if test -f $file
then
   echo "file exist"
fi

Example:- http://en.wikipedia.org/wiki/Test_(Unix)

Upvotes: 3

Gilles Quénot
Gilles Quénot

Reputation: 184965

You should take care of real location, because you can treat symlinks.

So I recommend this solution (readlink look-up for the real path)

#!/bin/bash

file="$(readlink -f $1)"   # file is the first argument of teh script
dir="$(readlink -f $2)"    # dir is the secong argument of the script

[[ -e "$dir/$file" ]] && rm -f "$dir/$file" # shortcut to rm the file if the test case is true

Upvotes: 0

Adam
Adam

Reputation: 3103

Look into the bash command test

You can use it by calling the command:

 test -f "$1"

$1 is the first argument passed to the script, or you can use the shortcut:

 [ -f "$1" ]

A sample script to check if a file exists:

 #!/bin/bash
 [ -f "$1" ] && echo "$1 exists" || echo "$1 does not exist"

Upvotes: 0

Related Questions