How to use ls -i on a different directory to get inodes of subdirectories matching a specific pattern?

Viewed 30

I would like to create a command that takes 3 args (directory to search in, pattern to match, and then file to create where data is written) but am a bit stuck because I can't figure out how to get inodes to show for these search results as well to be written in the file. It would be something like:

for i in "directory" if name = "pattern", inodes > "file"

like it should be simple and yet I cannot seem to get it? Here is what I have so far, but it doesn't show inodes (ls -i tends to show all subdirectories regardless of pattern match) and says my 3rd argument is too ambiguous...

#!/bin/bash

find "$1" -name "*$2*" > "$3"

I am wondering if I should be using something like ls /$directory -i but I feel like the syntax would not work.

1 Answers

You're close. You've got the searching part down. The missing piece is how to execute ls -i on the matching files. To do that, use -exec <command>, like so:

find "$1" -name "*$2*" -exec ls -i {} + > "$3"

The general syntax here is -exec <command> +, which executes command on all of the files that have been matched.

  • The {} curly braces at the end of the command are a placeholder. They tell -exec where in the command line to substitute the names of the matched files.
  • + is a marker for the end of the -exec action. Every -exec action must end with either + or ';'. + means "pass all of the files to a single invocation of command" and ';' means "call command multiple times, once per file".
  • If you use + then the curly braces have to be at the very end. The file names are all concatenated to the command. With ';' the {} can be anywhere, not just the end.

You might also want to use ls -id. By default ls will list the contents of directories. The -d flag tells it to list the directories themselves rather than what's inside them.

Related