Mac os symlink create

Works differently than a regular shortcut

A symbolic link, often shortened to symlink, is a type of link that is stored at one location on your machine and it points to another location on the same machine. You can think of it as a shortcut of an app. Even though the actual app file is located deep inside your folders, you can simply double-click on the app shortcut on your desktop to launch the app.

A symlink is a type of shortcut, but it works differently than regular shortcuts. It’s less of a shortcut and more of the actual file it’s pointing to. Any app that you provide with your symlinks will think of these links as the actual files rather than normal shortcut files.

These are extremely useful as you don’t have to be stuck to a particular folder for an app to work. You can have your data stored in other folders and you can create a symlink in the original folder pointing to the new folder you’ve created. Your system and your apps will think you haven’t really made any changes and they’ll work normally, although things are otherwise.

Making a symlink on a Mac is extremely easy. The built-in Terminal app has a command that lets you easily create as many symlinks as you want on your Mac.

All that you need to know is the location where you want to create the symlink and the path where the symlink should point to. Once you have this information, here’s how you create a symlink in Terminal.

Launch the Terminal app using your preferred way on your Mac.

Type in the following command into the Terminal window and hit Enter. Make sure to replace destination with the folder you want the link to point to and location with the path where you want to save the link.

ln -s destination location

To create a symlink on your desktop that points to your Documents folder, you’d use the following command:

ln -s /Users/Mahesh/Documents /Users/Mahesh/Desktop

A symlink will be created and saved on your desktop. Double-click on it and it’ll open the Documents folder (if that’s what you specified above) in the Finder.

If the directory you want to create a symlink for has spaces in its names, make sure to enclose the path names with double quotes so as to avoid any errors.

You can now use this symlink in any of your commands and apps and it’ll be considered as the actual version of your folder or file.

Terminal isn’t the only way to create symlinks on your Mac. If you don’t happen to be a Terminal guy, you have an app available to let you create symlinks on your machine.

What this app does is it adds an option to your context menu so you can create symlinks by just right-clicking on your files and folders.

Head over to the SymbolicLinker page on GitHub and download and open the package on your Mac.

Copy the SymbolicLinker.service.app file from the package, hold down the Option key, click on the Go menu in the Finder, select Library, open the Services folder, and paste the file you copied.

Double-click on the app to open it. It won’t show anything but it has secretly added an option to your context menu.

Читайте также:  Рейтинг мессенджеров для windows

Find the file or folder you want to create a symlink for, right-click on it, and select Services followed by Make Symbolic Link.

It’ll create the symlink in the same folder as the original file/folder. You can move it around though if you want.

The Automator method to create symlinks works pretty much the same way as the above method. But this one will suit those of you who don’t trust any random apps on the Internet, and you’d rather create something by yourself so you know exactly what it contains.

Launch the Automator app on your Mac.

Select Service followed by Choose to create a new Automator service on your Mac.

Set the options at the top as the following:

Service receives selected – files or folders

in – any application

In the actions list, search for the action named Run Shell Script and drag it over to the right panel.

Configure the action and the commands as the following:

Shell – /bin/bash

Pass input – as arguments

while [ $# -ne 0 ]; do
ln -s “$1” “$1 symlink”
shift
done

Save the service by clicking on the File menu at the top and selecting Save. Enter a meaningful name for the service and hit Save.

To create a symlink with the newly created Automator service, right-click on your file or folder and select Services followed by your service name.

You can also create a keyboard shortcut for the service to make creating symlinks even easier on your machine.

Symlinks don’t occupy much memory space as they’re just shortcuts to the files and folders on your machine. However, if you want to remove one or a few of these from your machine, you have two ways to do it.

Launch the Terminal app, type in the following command, and hit Enter. Make sure to replace symlink with the path of the symlink on your Mac.

rm symlink

Another way to delete a symlink is to use the context menu option. Right-click on your symlink and select Move to Trash. It’ll remove the symlink from your Mac.

Make sure to empty the Trash after you’re removed the symlink to ensure it’s gone for good from your Mac.

Conclusion

Symlinks are much more powerful than regular aliases as these work in all the apps and commands as if these were the real files.

Mahesh has been obsessed with technology since he got his first gadget a decade or so ago. Over the last few years, he’s written a number of tech articles on various online publications including but not limited to MakeTechEasier and Android AppStorm. Read Mahesh’s Full Bio

Источник

A symbolic link created at the command line allows a linked object in the file system to point to an original object in a different location. In this way, symbolic links behave much like an alias does in the Mac OS X GUI, except that the linking and reference between files or folders is done at a lower level, and thus can be pointed directly to by various applications or user purposes. This can be useful in many situations for advanced Mac users, from providing easier access to a particular location, to offloading an application folder to another hard drive, and much more.

To make and set a symbolic link at the command line in Mac OS X, you’ll want to use the ln command with the -s flag, without the -s flag a hard link is set, which is not what we’re looking to do here. Launch the Terminal to get started.

The basic syntax for creating a symbolic link (or soft link) is as follows:

ln -s /path/to/original/ /path/to/link

That will point /path/to/link to the original location, in this case /path/to/original/

For example, to create a symbolic link for the user Downloads folder which links it to a directory on a separate mounted drive, syntax may look like the following:

Читайте также:  Общая папка linux без пароля

ln -s /Volumes/Storage/Downloads/

That will link the active users

/Downloads/ folder to a directory named “Downloads” on the mounted drive called “Storage”. If such a directory and drive existed, this would basically allow all files that would typically appear in the user downloads folder to go to the other mounted volume instead, essentially offloading the storage burden to that separate drive, while still preserving the appearance of a

/Downloads/ folder for the user. As mentioned before, this behaves much like an alias.

Another example would be to offer easier access to an otherwise buried binary by linking the command to /usr/sbin/

sudo ln -s /A/Deeply/Buried/Path/ToApp.framework/Resources/command /usr/sbin/commmand

This would allow the user to type ‘command’ and access the binary, without having to prefix the command execution with the entire path.

Soft links have tons of potential uses, and if you’ve been a longtime reader of OSXDaily you’ve undoubtedly come across them before in other articles, from gaining easier access to the powerful airport command, placing mounted NTFS volumes onto the desktop, to moving local iTunes iPhone backup folders to external drives, to adding a Trash can icon to the user desktop like retro Mac OS versions, or even placing an application cache folder onto a RAM disk for ultra-fast data access and caching. The practical uses are countless, and making symbolic links will work in any unix OS, so beyond Mac OS X you could apply the same idea to linux or FreeBSD.

Of course, created symbolic links sometime need to be undone. This is easy with rm, or by using the ‘unlink’ command as follows:

Essentially this is removing the tiny file (again, like an alias) that references the symbolic link to the original item.

Unlinking a symbolic link will not delete any files or folders other than that defined link, it simply removes the reference from the linked item to the original item.

Know of any particularly great uses or tricks with symbolic links? Let us know in the comments!

Источник

Символические (символьные) ссылки в Mac OS X

Символические ссылки в Mac OS X позволяют создавать в удобном вам месте файл, который бы содержал в себе путь до искомого объекта файловой системы, сохраненного в другой папке или на другом диске. Это очень похоже на псевдоним файла, который можно создать при помощи Finder. Но, в отличии от псевдонимов, которые работают только на уровне Finder и не могут быть использованы в Терминале и UNIX-приложениях, символические ссылки работают на более глубоком уровне и могут иметь значительно больше применений. Они могут оказаться очень полезны для опытных пользователей компьютеров Mac при выполнении множества различных задач, начиная с упрощения взаимодействия с труднодоступными файлами и заканчивая переносом важных файлов и папок (например, папки «Программы») на внешний диск с сохранением функционала.

Для того чтобы создать символическую ссылку на нужный вам файл, потребуется прибегнуть к помощи Терминала.

  1. Запустите Терминал из папки «Утилиты»
  2. Введите команду ln -s /path/to/original//path/to/link где /path/to/original/ — путь к оригинальному файлу, а /path/to/link — путь к файлу, который будет содержать ссылку

Обратите внимание на флаг «-s». Он указывает на то, что мы создаем именно символическую ссылку, поэтому пропускать его не стоит. В противном случае мы создадим жесткую ссылку, которая содержит не путь к файлу, а его адрес в файловой системе (имя инода, о которых мы уже рассказывали ранее), что не подходит для выполнения большинства задач, которые обычно ставятся перед символическими ссылками.

Например, если мы хотим создать ссылку, указывающую на пользовательскую папку загрузок, которая хранится на другом диске мы можем ввести следующую команду: ln -s /Volumes/Storage/Downloads/

Таким образом, пользовательская папка «Загрузки» будет ссылаться на папку «Downloads», которая находится на диске с названием «Storage». В результате, если это папка существует, а диск подключен, все файлы, которые обычно сохранялись бы в стандартной папке «Загрузки» текущего пользователя будут появляться в папке «Downloads», что может помочь сэкономить место на загрузочном диске без существенных изменений в привычном порядке действий пользователя при загрузке файлов.

Стоит заметить, что при создании символической ссылки папки «Загрузки» уже не должно быть в пользовательской директории, иначе ссылка будет помещена в саму папку и не будет выполнять нужную нам функцию. Поэтому, стоит сначала скопировать папку в нужное вам место (например, на внешний диск), чтобы не потерять данные, а затем удалить ее из пользовательской директории командой в Терминале: sudo rm -rf

/Downloads/ После этого можно спокойно создавать символическую ссылку, как это показано выше.

Читайте также:  Iperf для windows как пользоваться

При помощи символических ссылок мы также можем упростить взаимодействие с труднодоступными файлами или скриптами:

sudo ln -s /A/Very/Long/Path/To/App.framework/Resources/command /usr/sbin/commmand

В результате пользователю достаточно будет ввести в Терминале «command» для запуска скрипта, без необходимости указывать полный путь к нему.

Применений для символьных ссылок можно найти бесчисленное множество. Например, если вы пользуетесь облачным хранилищем, вроде Dropbox, можно упростить процесc синхронизации важных для вас папок с этим сервисом, без необходимости переносить их в папку «Dropbox».

Для этого достаточно создать в папке «Dropbox» символические ссылки на те папки, содержимое которых вы хотите синхронизировать:

В результате введенной команды, содержимое папки «Документы» текущего пользователя будет синхронизирована с папкой «Documents» в Dropbox, а оригинальная папка останется на прежнем месте.

Удаление символических ссылок

По прошествии некоторого времени, или после выполнения определенных задач, часть созданных вами символических ссылок может оказаться не нужна. Оставлять их особого смысла нет, так как при необходимости их в любой момент можно создать заново, поэтому, если ссылка вам больше не нужна, вы можете с легкостью ее удалить, просто перетащив в корзину и очистив ее, как вы поступаете с любым другим ненужным файлом.

Вы также можете воспользоваться Терминалом. Для этого введите команду rm /path/to/symlink или unlink /path/to/symlink/ где /path/to/symlink/ — путь к файлу ссылки (не стоит путать с оригинальным файлом!).

В результате связь между оригинальным файлом и тем, который на него ссылается, будет удалена, как и сам маленький файл со ссылкой. При этом оригинал останется нетронутым.

Упрощаем процесс создания символических ссылок

Если использование Терминала вам кажется неудобным и вы бы хотели создавать символические ссылки через графический интерфейс, или же просто хотели бы упростить процесс создания ссылок, такая возможность тоже есть.

1. Сторонние программы

Для создания символических ссылок в Mac OS X можно воспользоваться уже готовыми программами сторонних разработчиков, например, SymLinker.

После загрузки, распакуйте архив и перенесите, содержащийся в нем файл приложения в папку «Программы», после чего запустите.

В результате на вашем экране возникнет окно программы. Интерфейс приложения довольно прост и запутаться в нем довольно сложно. В строке «Source» необходимо указать путь к файлу или папке, для которых вы хотите создать ссылку. Вы также можете нажать кнопку «Browse», чтобы не вводить путь вручную и выбрать искомый файл в открывшемся окне. Аналогичным образом необходимо ввести (или указать) место и имя для файла, в котором будет содержаться сама ссылка. После этого нажмите кнопку «Create» и ссылка будет создана.

Если же вы планируете использовать символические ссылки только для работы с облачными сервисами, вам могут помочь специализированные программы, такие как MacDropAny. Это программа создана специально и исключительно для того, чтобы синхронизировать с облачными сервисами папки и файлы, без непосредственного их перемещения.

2. Автоматизируем создание символических ссылок при помощи Automator

Вы можете упростить задачу создания символических ссылок и своими силами, при этом еще и добавив такую функцию в контекстное меню, которое появляется при нажатии на файл правой кнопкой мыши. Правда, для этого нам понадобится помощь Automator.

  1. Запустите Automator из папки «Программы»
  2. Выберите тип документа «Служба» и нажмите кнопку «Выбрать»
  3. В верхней части рабочей области укажите, что «Служба получает выбранное: файлы и папки в любой программе«
  4. С панели действий (слева) из библиотеки «Утилиты» перенесите элемент «Запустить shell-скрипт» в рабочую область приложения.
  5. У элемента «Запустить shell-скрипт» для параметры «Shell» укажите значение «/bin/bash«, а для «Передать ввод» выберите «Как агрументы», затем добавьте в тело элемента сам код скрипта:

Источник

Оцените статью