1

If I run touch non/existing/folder/my-file.txt, touch complains about non-existing folders.

Can I create these folders on the same command, similar to mkdir -p?

André Willik Valenti
  • 1,702
  • 14
  • 21

1 Answers1

1

No, but you can write a script that does that:

# new.sh
for file; do
  [[ $file =~ ((.+\/)*)(.+) ]] && mkdir -p "${BASH_REMATCH[2]}"
  touch $file
done

Then run: ./new.sh non/existing/folder/my-file.txt possibly/other/files.txt

André Willik Valenti
  • 1,702
  • 14
  • 21
  • That should really be `for file in "$@"` (or shorter: just `for file`); your version suffers from word splitting and parameter expansion. `${BASH_REMATCH[2]}` should be quoted as well. – Benjamin W. May 14 '20 at 00:01
  • Great suggestions! Is it ok now? PS: Found a good explanation of shell special variables here: https://stackoverflow.com/questions/5163144/what-are-the-special-dollar-sign-shell-variables – André Willik Valenti May 15 '20 at 12:56