How To Use Find Exec Command In Linux Bash?

Linux find command provides a lot of features to search and filter files in file system. One of the most popular and useful feature of find command is exec option. exec option is used to to run commands with founded search results.

Linux Find Command With Examples

Run Command

We will with a simple example where we will just provide single command to run with results. We will use -exec . In this example we will just print founded file names to the terminal. We will search for files with txt extension and print their names.

$ find . -type f -name "*.txt" -exec echo {} \;
Run Command 
Run Command 

Run Multiple Commands

We generally run single command to accomplish tasks. But in some cases we need to run multiple commands about the search result. We will specify multiple -exec options and command. In this example we will write the file name and grep for address.

$ find . -type f -name "*.txt" -exec echo {} \; -exec grep "address" {} \;
Run Multiple Commands
Run Multiple Commands

Remove Files

We can remove files by using -exec option with rm bash command. In this example we will also provide the recursive and force options for rm command. In this example we will delete all files with txtextension.

$ find . -type f -name "*.txt" -exec rm -Rf {} \;

Change Ownership Of Files

We can change ownership of files with -exec command. We will use chown command too. In this example we will change the ownership to the user ismail which have txt extension.

$ find . -type f -name "*.txt" -exec chown ismail {} \;


LEARN MORE  What Does "rm -rf" Command Do In Linux?

Leave a Comment