- Как удалить символические ссылки в Linux
- Прежде чем вы начнете
- Удалить символические ссылки с помощью команды rm
- Удалить символические ссылки с unlink
- Найти и удалить неработающие символические ссылки
- Заключение
- How To: Linux Delete Symbolic Link ( Softlink )
- Linux Delete Symbolic Link File
- Examples
- Getting confirmation prompt
- Delete Symbolic Link Directory
- Remove Symbolic Links with find command
- Find all symbolic links with find and delete them
- Finding and deleting broken symbolic links
- Again, we use the find command:
- Linux Remove Symbolic Link Command Options
- Conclusion
- how to delete symbolic links in linux
- delete symbolic link or soft symlink to a file
- using rm command
- using unlink command
- delete hard symbolic link to a file
- Using find command to delete all symbolic links in a directory
- Common Mistakes
- How to Remove Symbolic Link in Linux with Example
- rm and unlink commands to remove symbolic link
- Delete symbolic link file — Example
- Delete symbolic link directory — Example
- Conclusion
Как удалить символические ссылки в Linux
Главное меню » Операционная система Linux » Как удалить символические ссылки в Linux
В этой статье мы покажем вам , как удалить символические ссылки в системах Linux/UNIX с помощью команд rm, unlink и find.
Прежде чем вы начнете
Чтобы удалить символическую ссылку, вам необходимо иметь права на запись в каталог, содержащий символическую ссылку. В противном случае вы получите ошибку «Operation not permitted».
Когда вы удаляете символическую ссылку, файл, на который она указывает, не затрагивается.
Используйте команду ls -l, чтобы проверить, является ли данный файл символической ссылкой, и найти файл или каталог, на который указывает символическая ссылка.
Первый символ «l» указывает, что файл является символической ссылкой. Символ «->» показывает файл, на который указывает символическая ссылка.
Удалить символические ссылки с помощью команды rm
Команда rm удаляет указанные файлы и каталоги.
Чтобы удалить символическую ссылку, вызовите команду rm с символическим именем ссылки в качестве аргумента:
В случае успеха команда завершается с нуля и не выводит никаких данных.
С rm его помощью вы можете удалить более одной символической ссылки одновременно. Для этого передайте имена символических ссылок в качестве аргументов через пробел:
Чтобы получить запрос перед удалением символической ссылки, используйте параметр -i:
Для подтверждения нажмите клавишу y и нажмите Enter.
Если символическая ссылка указывает на каталог, не добавляйте косую черту / в конце. В противном случае вы получите ошибку:
Если имя аргумента заканчивается на /, команда rm предполагает, что файл является каталогом. Ошибка возникает из-за того, что при использовании без опции -d или -r rm yt удалит каталоги.
Чтобы быть в безопасности, никогда не используйте вариант -r при удалении символических ссылок с командой rm. Например, если вы введете:
Содержимое целевого каталога будет удалено.
Удалить символические ссылки с unlink
Команда unlink удаляет данный файл. В отличие от rm, unlink принимает только один аргумент.
Чтобы удалить символическую ссылку, запустите команду unlink с именем символической ссылки в качестве аргумента:
Если команда выполняется успешно, она не отобразит вывод.
Не добавляйте косую черту / в конце имени символической ссылки, потому что unlink не может удалить каталоги.
Найти и удалить неработающие символические ссылки
Если вы удалите или переместите исходный файл в другое место, символический файл останется висящим (сломанным).
Чтобы найти все неработающие символические ссылки в данном каталоге, выполните следующую команду:
Команда выведет список всех неработающих ссылок в каталоге и его подкаталогах.
Если вы хотите исключить символические ссылки, содержащиеся в подкаталогах, передайте параметр -maxdepth 1 в find:
После того, как вы найдете нарушенные символические ссылки, вы можете вручную удалить их с помощью команд rm, unlink или использовать опцию -delete в команде find:
Заключение
Чтобы удалить символическую ссылку, используйте команду rm или unlink, за которой следует имя символической ссылки в качестве аргумента. При удалении символической ссылки, указывающей на каталог, не добавляйте косую черту к имени символической ссылки.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
How To: Linux Delete Symbolic Link ( Softlink )
- rm command – Removes each given FILE including symbolic links in Linux.
- unlink command – Deletes a single specified file name including symbolic links in Linux.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Linux terminal |
Est. reading time | 4 minutes |
Let us see some examples about to remove (delete) symbolic links in Linux.
Warning : Care must be taken with the following rm, unlink, and find command as those commands won’t prompt for removal confirmation. The author or nixCraft site is not responsible for any data loss. Please use all command with care and think twice before you press the [Enter] key. Always keep a verified backup of all files and data.
Linux Delete Symbolic Link File
Use the following syntax:
Examples
First, we are going to create a new symbolic link in Linux using the ln command. Use the cd command to /tmp/ directory:
Now we are going to delete the dns symbolic link using the rm command or unlink command as follows:
Getting confirmation prompt
We can force prompt before every removal of symbolic links by passing the -i to the rm:
rm -i
Delete Symbolic Link Directory
The syntax is same:
Please avoid appending / at the end of linkDirName . cd in to the /tmp/ using the cd command:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Now delete the test symbolic link directory using any one of the following command:
Make sure symbolic link is removed using the ls command:
Remove Symbolic Links with find command
Here is we can search and list all symbolic links using the find:
Say list all symlinks in /tmp/bin/, run:
find /tmp/bin/ -type l -print
Only list *.txt or *.sh symlinks, run:
Find all symbolic links with find and delete them
All you have to do is replace the -print action with the -delete as follows to delete all ‘*.sh’ symlinks:
find /tmp/bin/ -lname «*.sh» -delete
To get confirmation use the following syntax when you need to find all “*.txt” symlinks and delete them:
Finding and deleting broken symbolic links
Again, we use the find command:
Here is what I see from the last command:
To remove that broken symlink, run:
Where find command options are:
- -type l : Find only symbolic link
- -lname «*.txt» :File is a symbolic link whose contents match shell pattern such as “*.txt”. Pass the -ilname «pattern» to the find for the case insensitive match. This option only works the latest version of GNU/find.
- -print : Print matched file lists.
- -delete : Remove/delete matched symlinks.
- -exec rm -i <> + : Remove/delete matched symlinks using the rm command with confirmation
- -xtype l : Deal with a symbolic link (find only symlinks).
- -ls : List symbolic links if found.
Linux Remove Symbolic Link Command Options
Type the following command:
rm —help
unlink —help
Conclusion
You learned the rm and unlink command to delete or remove a symbolic link under Linux operating systems. See the rm/unlink command man page by typing the following man command or read it online here:
man rm
man find
man unlink
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
how to delete symbolic links in linux
Symbolic links and symlinks are one of the most popular features of posix based Linux systems. The symbolic links gives you the ability to duplicate files in the system with different names and location with out the need to create copies of the file.
There are two different types of links that you can have in Linux: hard links and soft links. There are some major differences between the two types of links. But when talking about deleting a symbolic link, it is very likely that you are talking about deletion of a soft symbolic link.
Deleting a symbolic link is just as easy as creating a symbolic link or copying a symbolic link. This is because in Linux, links are nothing but files and works more or less like files. That means almost all operations that you can perform on a file can be done on a symbolic link as well.
There are essentially two commands that are used to delete or remove a symbolic link: the rm command and the unlink command.
delete symbolic link or soft symlink to a file
using rm command
The rm command is used to delete files and folders in linux. As links are files, the same command can be used to remove links as well. The command takes multiple file names as command line arguments. You can mix and match files and links in the same command as well.
By default, the command will not output any messages unless there is an error. All the command line options of the rm command is applicable in this case as well. You can use the -i or –interactive option to prompt before every removal.
using unlink command
I mostly use rm command to remove symbolic links and never the unlink command. But unlink is another command that can be used to remove links. The unlink command takes only one command line argument which is the link name.
The unlink command is less powerful than the rm command and therein lies its advantage. It is much more advisable to use unlink command from with in shell scripts than the rm command. This will make sure that files and folders are not accidently deleted when running scripts.
As you should already be aware, the directories or folders in linux and nothing but files. That means you can use essentially the same commands as above to delete links to folders. However, there is a caveat that you should keep in mind when the link points to a folder.
The link name is the name of the link without the trailing forward slash. If you specify the forward slash then it refers to the actual folder and not the link itself. That means it will try to delete the actual contents of the folder rather than the link itself. In most cases, this should throw an error unless you have specified the -r or –recursive and -f or –force command line option with the rm command.
delete hard symbolic link to a file
As we mentioned the hard symbolic link earlier in the post, let’s see how you would delete a hard symbolic link. For most practical purposes, hard links are pretty transparent to file operations even more so than soft links. That means you just treat the hard links just as a file, and delete them just the same way as the files or soft links.
Using find command to delete all symbolic links in a directory
If you want to delete all symbolic links in a folder and its sub-folders, then you can use the find command. You can use it to first find all the symbolic links and then to delete it.
- -type: the type of file. l represents the link
- -delete: the delete file action
Common Mistakes
There are some common precautions you should have when deleting links and probably deleting files and folders in general. This will avoid accidently deleting the wrong files.
- If running from command line, always use the -i option. Actually, you can create a bash alias so that it is the default and override it only when you need.
- Do not use the forward slash at the end of file and folder names. In the case of links pointing to a folder, it will reference the actual folder and not the symbolic link.
- Use the rm command sparingly and wisely in the shell scripts. It is very easy to get the arguments wrong and delete the wrong files.
Источник
How to Remove Symbolic Link in Linux with Example
Symbolic links or Soft links work like pointers to another file. Note that there is only one copy of the actual file on the hard disk and in this way you can save valuable hard disk space by simply creating a link to it. Deleting a symbolic link is the same as removing a real file or directory.
A symbolic link is a link that refers to the name of a file. Its most important advantage is that it can be used to refer to a file that is anywhere, even on a computer on the other side of the world. The symbolic link will still work. However, the biggest disadvantage is that the symbolic link is naturally dependent on the original file. There are some properties of symbolic links
- Links have different inode numbers : every Linux file or directory (from a technical point of view, there’s no real difference between them) has an inode and this inode contains all of the file’s metadata (that is, all the administrative data needed to read a file is stored in its inode)
- ls -l command shows all links with second column value 1 and the link points to original file.
- Link contains the path for original file and not the contents.
- Removing soft link doesn’t affect anything but when the original file is removed, the link becomes a dangling link that points to nonexistent file.
rm and unlink commands to remove symbolic link
Symbolic links can be removed with two commands: rm and unlink. You can use any one of the following commands to remove symbolic links.
- rm: is the terminal command to remove each given file including symbolic links. Because a symbolic link is considered as a file on Linux, you can delete it with the rm command.
- unlink: deletes a single specified file name including symbolic links.
To remove the symbolic link file, you should list it with ls -l command as below
pac -> /root/pac shows the path of the original file which is /root/pac and the 1 value on the second column indicates that the file is a symbolic link file.
Delete symbolic link file — Example
To see how we can delete symbolic link file, we will first create a soft link a below
To list how soft link looks:
To delete symbolic link, you can use its relative or absolute path but to limit error, I recommend you to use a relative path.
With absolute path we have
We can check as below
With relative path, we first need to move to the symbolic link file directory
Now you can use one of the commands above
Be careful when you use unlink command because it can delete regular file. If you write an existing regular filename instead of a symbolic link filename, the regular file will be deleted. See below
You can see that file1 is not a symbolic link. Now we will use unlink command and we will see the result.
You see that file1 doesn’t exist. It has been deleted
Delete symbolic link directory — Example
To delete a symbolic link directory, we will use the same procedure as above. We will create a soft link:
pac is the folder which will be used for the test.
Now to delete the test symbolic link directory, we will use the relative path. We have moved to /home/papso/test folder
We will check now with absolute path
unlink command and rm command without -R option doesn’t delete regular directory. The two commands delete symbolic link from directory because it’s considered as a file so, when using the rm or unlink command to remove a symbolic link from a directory, make sure you don’t end the target with a / character because that will create an error.
Now let’s try to delete the symbolic link
Because the / at the end indicates a directory, the command doesn’t work
Now let’s try without the / character at end of the filename
Now let’s check it the file exists
You can see that the symbolic link has been deleted
Conclusion
Basically, a symbolic link makes it easier to find files you need. You can create symbolic links for the files, directories and you can use them to make life easier for users as well. Symbolic link is considered as a normal file because you can delete it with the basic rm command. Don’t forget the biggest disadvantage which imply that the symbolic link is naturally dependent on the original file.
Источник