How can I use the same wildcard in different parts of a command?

Say I have the following command which creates a symbolic link from one file to another giving the link the same name without the extension.

sudo ln -s ~/foobar/abc.sh ~/fubar/abc

How can I do the same thing, but for ~/foobar/*.sh?


Renaming files, and in your case, creating symlinks, mmv will suffice.

mmv -s '~/foobar/*.sh' '~/fubar/#1'
  • -s For the resulting link to aim back at the source, either the source name must begin with a '/', or the target must reside in either the current or the source directory. If none of these conditions are met, the link is refused. However, source and target can reside on different devices and the source can be a directory.

for fn in ~/foobar/*.sh ; do
sudo ln -s $fn ~/fubar/`basename $fn .sh`
done

This assumes that none of the *.sh files has spaces if the filename. If it does, you need to quote both arguments to ln -s command:

for fn in ~/foobar/*.sh ; do
sudo ln -s "$fn" "~/fubar/`basename $fn .sh`"
done