2

I want to run two commands but the second command depends on the first.

Is there a way to do something like this.

 find . -name '*.txt' -exec  'y=$(echo 1); echo $y' {} \;

...

And actually, I want to do this. Run the find command, change to that directory that the file is in and then run the command on the file in the current directory.

find . -name '*.txt' -exec 'cd basedir && /mycmd/' {} \;

How do I do that?

2 Answers 2

3

find actually has a primary that switches to each file's directory and executes a command from there:

find . -name '*.txt' -execdir /mycmd {} \;
Sign up to request clarification or add additional context in comments.

Comments

1

Find's -exec option expects an executable with arguments, not a command, but you can use bash -c cmd to run an arbitrary shell command like this:

find . -name '*.txt' -exec bash -c 'cd $(dirname {}) && pwd && /mycmd $(basename {})' \;

I have added pwd to confirm that mycmd executes in the right directory. You can remove it. dirname gives you the directory of each file and basename gives you the filename. If you omit basename your command will receive (as {}) pathname to each file relative to the directory where you run find which is different from mycmd's current directory due to cd, so mycmd will likely fail to find the file. If you want your command to receive absolute pathname, you can try this:

find $PWD -name '*.txt' -exec bash -c 'cd $(dirname {}) && pwd && /mycmd {}' \;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.