22

If I have a directory /foo with a few files in it, how do I symlink each entry in /foo into /bar/?

For instance, if /foo has the files a, b and c, I want to create three symlinks:

  • /bar/a -> /foo/a
  • /bar/b -> /foo/b
  • /bar/c -> /foo/c
3
  • Are you sure you don't just want to symlink bar to foo? Feb 11, 2011 at 17:18
  • The actual application of this is that I installed a program and would like to move its executables to a standard folder in my $PATH rather than add the installed one to the path.
    – Steven
    Feb 11, 2011 at 17:21
  • It seems like it would be a better idea to just configure it with --prefix=.
    – Hello71
    Feb 12, 2011 at 18:15

3 Answers 3

21

You can use (GNU) cp with the --symbolic-link option:

prompt$ mkdir foo
prompt$ cd foo
prompt$ touch a b c
prompt$ mkdir ../bar
prompt$ cd ../bar
prompt$ cp --symbolic-link ../foo/* .
prompt$ ls -l
total 0
lrwxrwxrwx. 1 hlovdal hlovdal 8 Jun 12 16:24 a -> ../foo/a
lrwxrwxrwx. 1 hlovdal hlovdal 8 Jun 12 16:24 b -> ../foo/b
lrwxrwxrwx. 1 hlovdal hlovdal 8 Jun 12 16:24 c -> ../foo/c
prompt$
4
  • This seems to be exactly the solution. Awesome!
    – Steven
    Jun 12, 2011 at 16:07
  • This is very perfect.
    – noraj
    Dec 28, 2018 at 20:48
  • any way to make this apply for directories as well? When I run this I get warning "cp: omitting directory './baz'"
    – solidau
    Sep 13, 2019 at 17:04
  • @solidau Answer of PausedUntilFurtherNotice. does it.
    – robsch
    Feb 6, 2020 at 17:13
25

Give this a try:

ln -s /foo/* /bar

The source directory, as specified in the question, is /foo. Note that it must be fully specified (i.e. starting at the root directory), so other examples would look like this:

ln -s /some/dir/with/baz/* destdir
ln -s /dir/to/link/from/* /dir/to/link/to
ln -s $PWD/stuff/* more/stuff
5
  • does this even work?
    – ctrlc-root
    Aug 3, 2015 at 18:06
  • @root.ctrlc: You have to specify the full path of the source (which is / in my original answer). I'll add a clarification. Aug 3, 2015 at 18:14
  • I think if you want to copy everything as symlink with one command only, you have to use cp -s like @hlovdal answer, cp -rs /var/www/folder/ . copies every subfolders files as symlink, not like ln -s /var/www/folder/ . who duplicated subfolders files on my computer.
    – baptx
    Nov 28, 2015 at 18:54
  • If anyone needs that: hidden files can be symlinked in a second step with ln -s /foo/.* /bar.
    – robsch
    Feb 6, 2020 at 17:15
  • great best answer
    – acgbox
    Aug 2, 2021 at 16:01
2

Something like this?

cd /foo
for f in *; do ln -s $PWD/$f /bar; done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .