Sample Header Ad - 728x90

Dash gives error "sh: 1: cannot create : Directory nonexistent"

0 votes
2 answers
1403 views
I am running the following script in Ubuntu 22.04:
#!/bin/bash

logfile="/absolute/path/to/log.txt"
find /absolute/path/to/haystack -type d -name "needle" -execdir sh -c 'pwd > $logfile' \;
The hope is that it would print the full directory path of each folder named needle/ within the folder haystack/ to the file log.txt. Instead, it prints nothing but a long list of the error sh: 1: cannot create : Directory nonexistent to the standard output (and it writes nothing to log.txt). This [answer](https://stackoverflow.com/a/66653290/) demonstrates that the error originates in Dash, not Bash. Since I'm using the Bash shebang, this means the error must stem from the use of -execdir sh
-execdir sh -c 'pwd > $logfile' \;
since in Ubuntu sh is symlinked to Dash. My first theory was that Bash isn't passing its variable $logfile to Dash. This [answer](https://unix.stackexchange.com/a/737106/) states that variables are copied to subshells, which was my understanding, but perhaps that doesn't hold true across completely different shells. To test it, I changed the shebang to #!/bin/sh, which is Dash on this system. The result is the same, however: rows of the error sh: 1: cannot create : Directory nonexistent. **What causes this error to happen?** Any help is appreciated, but please note that I've posted because I want to understand the origin of the error, just as the question asks. I'm not interested in any answer that takes a different approach to listing needle/ directories, unless that answer is accompanied by an explanation of why this script fails.
Asked by Borea Deitz (170 rep)
Aug 29, 2024, 07:19 PM
Last activity: Aug 30, 2024, 04:15 PM