2

I am trying to check if a file path exists and if it does to complete the pwd command. if a file path does not exist then i want it to break and move on to the next command.

while [ -d folder1/*/stack ]; do pwd; break; done; while [<next set of commands>]...ect

i get binary operator expected error.

Lucas Muller
  • 101
  • 9
  • 1
    That's because `-d` expects a single filepath to evaluate, you can't use globbing within `[ -d ... ]`. A quick hack would be `[ $(find folder -type d -name "stack" -printf "." | wc -c) -gt 0 ]` Which just prints a `'.'` for each directory named `"stack"` found below `./folder` and then counts the dots with `wc -c` and tests whether the result is greater than zero. You can add `-maxdepth 2` to limit the descent of `find` further below the `stack` level. – David C. Rankin Oct 11 '20 at 03:57
  • 1
    More accurately, you can't _reliably_ use globbing within the test operation `[ -d folder1/*/stack ]` because: (1) there might not be any match, so the second argument would be `folder1/*/stack` and the test would fail (not a problem); (2) there might be a single match, so the second argument might be `folder1/subdir1/stack`, which might be a directory, so the test would work as intended; (3) there might be several names that match, in which case there would be extraneous arguments to the test, such as `[ -d folder1/subdir1/stack folder1/subdir2/stack ]` which is an invalid use of the test. – Jonathan Leffler Oct 11 '20 at 04:06
  • 2
    Maybe you want: `shopt -s nullglob; for directory in folder1/*/stack; do … done` where you'd need to check that `"$directory"` actually is a directory in the loop. Note that using `for directory in folder1/*/stack/` with a trailing slash does limit the result set to actual directories. See the Bash manual on [The Shopt Builtin](https://www.gnu.org/software/bash/manual/bash.html#The-Shopt-Builtin). – Jonathan Leffler Oct 11 '20 at 04:10
  • Possible duplicate of ["Test whether a glob has any matches in bash"](https://stackoverflow.com/questions/2937407/test-whether-a-glob-has-any-matches-in-bash). Also the Unix&Linux question ["Test if there are files matching a pattern in order to execute a script"](https://unix.stackexchange.com/questions/79301/test-if-there-are-files-matching-a-pattern-in-order-to-execute-a-script). – Gordon Davisson Oct 11 '20 at 04:47

1 Answers1

2

You can use ls. If ls is successfull, then pwd will run:

ls folder1/*/stack > /dev/null 2>&1 && pwd
# next command
Oliver Gaida
  • 1,722
  • 7
  • 14