0

I have this command:

dest=folder
files=$(find -type f -not -path $dest)

mkdir -p "$PWD/$dest"
for file_path in $files; do 
    filename="$file_path" 
    echo$file_path >> list.txt
done 

this returns a file: /path/this is a test.txt in list.txt as:

/path/this

is

a

test.txt

what i want is: /path/this is a test.txt

or even better with "/" replaced with "-" and the first one completely removed: path-this is a test.txt any ideas what the problem here is and how to fix it?

Daniel
  • 113
  • 1
  • 1
  • 7
  • Don't store lists of filenames in string variables at all. They're entirely unsuited to the job. – Charles Duffy Jul 22 '20 at 21:24
  • Remember, **any character except a NUL is valid in a filename**. And likewise, any character except a NUL is valid in a shell string. That means you can have a filename with a newline in its name, for example. – Charles Duffy Jul 22 '20 at 21:24
  • So there's no possible way to know if you have one filename called `foobar`, or two separate filenames, `foo` and `bar`. – Charles Duffy Jul 22 '20 at 21:25
  • ...so, `find -type f -not path $dest` is itself hopelessly, unfixably broken. This is covered in [BashPitfalls #1](http://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29). Use NUL-delimited streams to represent your filenames, and parse them into bash arrays, not bash string variables, when you want to store them as a list. – Charles Duffy Jul 22 '20 at 21:26
  • Also see [UsingFind](https://mywiki.wooledge.org/UsingFind), which covers safe practices for using `find` as well. Note in particular the guidance to always use either `-print0` or `-exec` actions to pass names out of `find` in unambiguous form (`-exec` passes values as C strings, which are implicitly NUL-delimited; `-print0` is _explicitly_ NUL-delimited). – Charles Duffy Jul 22 '20 at 21:27
  • There's also [BashFAQ #5](https://mywiki.wooledge.org/BashFAQ/005), for a general introduction on using arrays in bash. – Charles Duffy Jul 22 '20 at 21:28
  • See also [How can I store the "find" results as an array in bash?](https://stackoverflow.com/questions/23356779/how-can-i-store-the-find-command-results-as-an-array-in-bash) – Charles Duffy Jul 22 '20 at 21:29
  • ...actually, I'm tempted to close this as a duplicate of that -- its accepted answer completely addresses and resolves your problems. The only real qualm I have with it is that `$'\0'` is misleading -- it implies that you *can* pass a NUL as a literal in bash, which is false; `$'\0'` is 100% identical to just `''`. Both act as NULs only in a context where the first character of a string is what's being read, because C strings are NUL-terminated, so for a zero-length string, the first and only character used in its representation in memory is... the terminating NUL. – Charles Duffy Jul 22 '20 at 21:29

0 Answers0