Suzie
Suzie

Reputation: 113

How to use command line arguments with find in bash script?

I have a hard time writing simple script using find command. I want to delete files with given size in some directory. I want to be able to specify names of files (like Efficiency_*) and size of files to delete. I tried following script:

#!/bin/bash
CD=($pwd)
find $CD -name $1 -size $2 -delete

I am running it from the correct directory as follows:

/path/to/directory/script.sh 'Efficiency_*' '-500c'

but it does not work.

What is the correct way to do it?

Upvotes: 1

Views: 9651

Answers (2)

OkieOth
OkieOth

Reputation: 3704

The problem is the value you give to the CD-variable. In Bash scripts you have two different ways to assign the output of a program call to a variable ...

# method 1
CD=`pwd`

# method 2
CD=$(pwd)

Upvotes: 1

Barmar
Barmar

Reputation: 780655

You don't need the CD variable, just use . to refer to the current directory.

And the other variables need to be quoted. Otherwise, the shell will expand the wildcard instead of passing it to find.

#!/bin/bash
find . -name "$1" -size "$2" -delete

In general, you should always quote variables unless you have a specific reason not to.

Upvotes: 5

Related Questions