-1

Im learning bash and I'm trying to perform a for loop on directories, the end result im trying to achieve is if there is only one subdirectory i want to move it to another directory.

However, in its current state I have it where the for loop will get each directories subdirectory count, and I'm attempting to simply echo directories that only have 1 subdirectory, but chaining an if statement fails with "bad pattern" error. Does anyone know what im doing wrong?

for dir in ./dir/*; do output=$(ls -l $dir | grep -c ^d) && if [$output -eq 1]; then echo $dir; fi; done
polar
  • 524
  • 5
  • 24
  • 1
    [Shellcheck](https://www.shellcheck.net/) finds a serious problem in the code (missing spaces). The report includes a link to more information about the problem and how to fix it. It's a good idea to run [Shellcheck](https://www.shellcheck.net/) on all new and modified shell code. – pjh Aug 26 '23 at 23:24
  • @pjh yes it does, and thank you for the shellcheck resource! – polar Aug 26 '23 at 23:26
  • 1
    Instead of `ls`, you can use the glob `./dif/*/` for listing the directories only – Fravadona Aug 26 '23 at 23:26
  • 1
    See [Why you shouldn't parse the output of ls(1)](http://mywiki.wooledge.org/ParsingLs) for information about difficulties associated with trying to extract information from `ls` output. – pjh Aug 26 '23 at 23:32

0 Answers0