- How To Create Symlinks On Your Mac
- Creating a Symlink Using The Terminal
- Use An App To Create a Symlink
- Create Symlinks Using An Automator Service
- Deleting a Symlink On Mac
- Conclusion
- How to Create Symbolic Links at Command Line of Mac OS X
- How to Make a Symbolic Link
- Example Syntax for Making Soft Links at the Terminal
- How to Remove a Symbolic Link
- Как создавать и использовать символические ссылки (или символические ссылки) на Mac
- Что такое символические ссылки?
- Создание символических ссылок с помощью команды ln
- Как удалить символические ссылки
- Как создать символические ссылки с помощью графического инструмента
How To Create Symlinks On Your Mac
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.
Creating a Symlink Using The Terminal
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.
Use An App To Create a Symlink
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.
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.
Create Symlinks Using An Automator Service
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.
Deleting a Symlink On Mac
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
Источник
How to Create Symbolic Links at Command Line of Mac OS X
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.
How to Make a Symbolic Link
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/
Example Syntax for Making Soft Links at the Terminal
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:
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.
How to Remove a Symbolic Link
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
Символические ссылки, также известные как символические ссылки, представляют собой специальные файлы, которые указывают на файлы или каталоги в других местах вашей системы. Вы можете думать о них как о расширенных псевдонимах, и вот как их использовать в MacOS.
Символьные ссылки похожи на псевдонимы, за исключением того, что они работают во всех приложениях на вашем Mac, включая терминал. Они особенно полезны, когда приложения не хотят работать правильно с обычным псевдонимом. В macOS вы создаете символические ссылки в Терминале с помощью утилиты ln . Вы не можете создать их в Finder. Символические ссылки в macOS работают аналогично символическим ссылкам в Linux , поскольку обе являются Unix-подобными операционными системами. Символические ссылки в Windows работают немного по-другому.
Что такое символические ссылки?
В macOS вы можете создавать обычные псевдонимы в Finder. Псевдонимы указывают на файлы или папки, но они больше похожи на простые ярлыки.
Символьная ссылка — это более продвинутый тип псевдонима, который работает в каждом приложении в системе, включая утилиты командной строки в терминале. Символическая ссылка, которую вы создаете, кажется приложениям такой же, как исходный файл или папка, на которую она указывает, даже если это просто ссылка.
Например, допустим, у вас есть программа, файлы которой должны храниться в / Library / Program. Но вы хотите хранить эти файлы где-то еще в системе, например, в / Volumes / Program. Вы можете переместить каталог Program в / Volumes / Program, а затем создать символическую ссылку в / Library / Program, указывающую на / Volumes / Program. Программа попытается получить доступ к своей папке в / Library / Program, а операционная система перенаправит ее в / Volumes / Program.
Это полностью прозрачно для операционной системы MacOS и приложений, которые вы используете. Если вы перейдете в каталог / Library / Program в Finder или в любом другом приложении, он будет содержать файлы в / Volumes / Program.
В дополнение к символическим ссылкам, которые иногда называют «мягкими ссылками», вы можете создать «жесткие ссылки». Символическая или программная ссылка указывает на путь в файловой системе. Например, допустим, у вас есть символическая или мягкая ссылка из / Users / example, указывающая на / opt / example. Если вы переместите файл в / opt / example, ссылка на / Users / example будет разорвана. Однако, если вы создадите жесткую ссылку, она фактически будет указывать на базовый индекс в файловой системе. Итак, если вы создали жесткую ссылку из / Users / example, указывающую на / opt / example, а затем переместили / opt / example, ссылка в / Users / example все равно будет указывать на файл, независимо от того, куда вы его переместили. Жесткая ссылка работает на более низком уровне.
Обычно вы должны использовать стандартные символические ссылки (программные ссылки), если вы не уверены, какой из них использовать. Жесткие ссылки имеют некоторые ограничения. Например, вы не можете создать жесткую ссылку на один раздел или диск, указывающую на местоположение в другом разделе или диске, в то время как вы можете сделать это с помощью стандартной символической ссылки.
Создание символических ссылок с помощью команды ln
Чтобы создать символическую ссылку на Mac, вам нужно использовать приложение «Терминал».
Нажмите Ctrl + Пробел, введите «Терминал», а затем нажмите «Ввод», чтобы открыть Терминал из поиска Spotlight. Перейдите в Finder> Приложения> Утилиты> Терминал, чтобы запустить ярлык терминала.
Запустите команду ln в следующей форме. Вы можете указать путь к каталогу или файлу:
Здесь -s указывает команде ln создать символическую ссылку. Если вы хотите создать жесткую ссылку, вы должны опустить -s . В большинстве случаев символические ссылки являются лучшим выбором, поэтому не создавайте жесткую ссылку, если у вас нет для этого конкретной причины.
Вот пример. Допустим, вы хотите создать символическую ссылку в папке «Рабочий стол», которая указывает на папку «Загрузки». Вы бы запустили следующую команду:
После создания ссылки на вашем рабочем столе появится папка «Загрузки». На самом деле это символическая ссылка, которую вы создали, но она будет выглядеть как настоящая. Эта папка будет содержать все те же файлы, что и ваша папка «Загрузки». Это потому, что это так — это просто разные представления, указывающие на один и тот же базовый каталог в файловой системе.
Если путь к файлу содержит пробелы или другие специальные символы, его необходимо заключить в кавычки. Итак, если вы хотите создать ссылку на рабочем столе на папку с именем «Мои файлы» в вашем пользовательском каталоге, вам понадобится что-то вроде следующей команды:
Чтобы упростить ввод путей к файлам и каталогам в Терминале, вы можете перетащить папку из окна Finder в Терминал, и Терминал автоматически заполнит путь к этой папке. При необходимости он также будет заключен в кавычки.
Если вам нужно создать символическую ссылку в системном расположении, к которому ваша учетная запись пользователя не имеет доступа, вам нужно добавить префикс команды ln команде sudo , например, так:
Имейте в виду, что в современных версиях macOS вам не разрешат выполнять запись в определенные местоположения системы без изменения опции встроенного ПО низкого уровня из-за функции защиты целостности системы . Вы можете отключить эту функцию, но мы рекомендуем этого не делать.
Как удалить символические ссылки
Вы можете удалить символические ссылки, как и любой другой тип файла. Например, чтобы удалить символическую ссылку в Finder, нажмите Ctrl + щелкните или щелкните ее правой кнопкой мыши и выберите «Переместить в корзину».
Вы можете удалить ссылки из командной строки, используя команду rm , которая является той же командой, которую вы использовали бы для удаления других файлов. Запустите команду и укажите путь к ссылке, которую вы хотите удалить:
Как создать символические ссылки с помощью графического инструмента
Finder может создавать псевдонимы, но они не будут работать как символические ссылки. Псевдонимы аналогичны ярлыкам на рабочем столе Windows. Они не рассматриваются как настоящие, прозрачные символические ссылки.
Чтобы иметь возможность создавать символические ссылки в Finder, вам понадобится сторонняя утилита или скрипт. Мы рекомендуем приложение с открытым исходным кодом SymbolicLinker для быстрого добавления параметра Сервисы> Сделать символическую ссылку прямо в контекстное меню Finder.
Выберите опцию, которую он добавляет, и он создаст символическую ссылку на выбранный файл или папку в текущем каталоге. Вы можете переименовать его и переместить куда угодно.
Если вы не использовали их раньше, символические ссылки могут занять некоторое время, чтобы обернуться и привыкнуть к использованию. Но, как только вы это сделаете, вы найдете их мощным инструментом для выполнения того, что вы часто не можете сделать с обычным псевдонимом.
Источник