Use `ln` to create a missing directory

16,450

Solution 1

You won't need a convoluted bash script, but a simple one-liner. mkdir --parents will take care of everything, nicely not even printing an error if the directory structure already exists.

Just be careful with how you treat these directories on removal, so you don't break other packages.

Also, since you're writting it in bash, you can take a look at sorcery (shameless plug). Maybe it would be simpler to just modify that, as it is mature and flexible.

Solution 2

There's no flag to do this with ln. Creating directories is not its job.

mkdir -p foo/bar/qux will create foo, foo/bar and foo/bar/qux as needed. So call mkdir -p on all but the last path component first.

It sounds like you're reinventing the wheel Stow, a simple package manager that merges directory hierarchies by creating directories to the required depth with symbolic links to components of different packages inside. Or perhaps XStow, which is like Stow but with more customization possibilities.

Share:
16,450

Related videos on Youtube

Chris
Author by

Chris

Updated on September 18, 2022

Comments

  • Chris
    Chris almost 2 years

    So I'm writing a small package manager, and a problem I've run into is making the symbolic links to files.

    It installs the package to /usr/pkg/name-version, and then reads a file to determine what symbolic links to make. I'm using ln to make the links, and I've run into a problem when trying to install the Linux API headers. I need to link the header files themselves, not the folders that contain them (so if 2 packages need to put files in the same subdirectory of include they can without screwing one package up).

    That problem I solved, but ln simply errors out if the path is incomplete, which is annoying because those directories shouldn't exist until the package is installed.

    Is there a flag for ln that will create any directories that are missing, or am I going to have to go with some convoluted bash script?

    • jw013
      jw013 almost 12 years
      I may be missing something obvious, but why aren't you using mkdir to ... make directories?
    • ams
      ams almost 12 years
      You might also want to check out lndir.
  • Lie Ryan
    Lie Ryan over 8 years
    @Chris: system() isn't more easy, it's very hard to escape command line arguments properly with system(). At the very least you should use posix_spawn() or fork()+exec*(), which accepts command line arguments as arrays.