0

Variable causing issue while doing the test command in unix Command is::

find $PWD -type d -exec sh -c 'test "{}" ">" "$PWD/$VersionFolders"' \; -print|wc -l`

Input Values-

Here $PWD- Current Directory

b1_v.1.0 b1_v.1.2 b1_v.1.3 b1_v.1.4

Given Version folder as $VersionFolders b1_v.1.2

The Command should check if any folders exist in current directory which is greater than the give version folder and it should count or display. This approach has to be consider with out date or time created of folders.

Expected Output- b1_v.1.3 b1_v.1.4

If I give hard code Directories its working fine. But when I pass it like as variable.it give all folders.

working fine this commend-

find $PWD -type d -exec sh -c 'test "{}" ">" "$PWD/b1_v.1.2"' \; -print|wc -l`

Not working this command with variable- find $PWD -type d -exec sh -c 'test "{}" ">" "$PWD/$VersionFolders"' ; -print|wc -l`

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • Are you sure the value of `VersionFolders` doesn't have anything like a stray carriage return or whitespace at the end of the value? – chepner Oct 08 '22 at 19:51
  • Don't embed `{}` in the command to execute; let `find` pass the filename represented by `{}` as an argument to the command instead: `... -exec sh -c 'test "$1" ">" "$PWD/$VersionFolders"' _ {} \;`. For that matter, you don't need `sh`, since `test` is *already* a command that `find` can execute: `... -exec test {} ">" "$PWD/$VersionFolders" \;`. – chepner Oct 08 '22 at 19:53

1 Answers1

0

The variable $VersionFolders won't get expanded inside the single quotes, and apparently you did not export it to make it visible to subprocesses.

An obscure but common hack is to put it in $0 (which nominally should contain the name of the shell itself, and is the first argument after sh -c '...') because that keeps the code simple.

find . -type d \
  -exec sh -c 'test "$1" ">" "$0"' \
    "$VersionFolders" {} \; \
  -print | wc -l

But as @chepner remarks, you can run -exec test {} ">" "$VersionFolders" \; directly.

The shell already does everything in the current directory, so you don't need to spell out $PWD. Perhaps see also What exactly is current working directory?

tripleee
  • 175,061
  • 34
  • 275
  • 318