Linux symlink folder to folder

Содержание
  1. How to Create Symbolic Links in Linux
  2. What are Linux Symbolic Links
  3. How to Create Symbolic Links in Linux?
  4. Create Symbolik Link in Linux for Files
  5. Create Symbolic Link in Linux for Folders
  6. How to Change or Remove Symbolic Link in Linux?
  7. Wrapping up
  8. linux-notes.org
  9. Создание ссылок (symlink) в Unix/Linux
  10. Symlink Tutorial in Linux – How to Create and Remove a Symbolic Link
  11. Difference Between a Soft Link and a Hard Link
  12. How to Create a Symlink
  13. How to Create a Symlink for a File – Example Command
  14. How to Create a Symlink for a Folder – Example Command
  15. How to remove a symlink
  16. How to Use Unlink to Remove a Symlink
  17. How to use rm to Remove a Symlink
  18. How to Find and Delete Broken Links
  19. Wrapping up
  20. Linux zip folder | 16 practical Linux zip command examples
  21. Linux Zip Command Examples
  22. Pre-requisite:
  23. Install zip
  24. Install unzip
  25. 1. How to zip a folder with multiple files Linux
  26. 2. How to create a zip file by excluding some files
  27. 3. How to zip a folder by compressing directory and sub-directories
  28. 4. How to display zip archive content
  29. 5. How to zip a folder with password protection
  30. 6. How to update or modify existing file in zip archive
  31. 7. How to add files to existing zip archive
  32. 8. How to list zip archive contents without extracting
  33. 9. How to create a zip file without complete path (Store only the file name)
  34. 10. How to create a zip file and delete original files after archiving
  35. 11. How to zip a folder with higher compression level
  36. 12. How to copy files between two zip archives
  37. 13. Linux zip directory and remove files from zip archive
  38. 14. Linux zip folder and preserve symbolic links
  39. Unzip to directory using unzip command
  40. 15. How to create a zip file and compress with bzip2
  41. Extract content using unzip command
  42. 16. How to zip a folder and later split zip archive
  43. References:
  44. Related Posts

Learning Linux symbolic commands is a great way of improving your potential in the Linux terminal. In this tutorial, we’ll cover a few commands to learn symbolic links in a quick and easy way. Before we begin, let’s overview what are symbolic links.

Symbolic Links are not only helpful in creating shortcuts and file management in operating systems like Linux. They also serve as a way to create various locations for primary user folders, for instance, Documents, Pictures, Downloads, and much more!

Symbolic Links act like a string creating pathways for different files, folders, and directories in the computer system. They are capable of creating and storing multiple files in different places refer to one single file. Thus, increasing efficiency by locating all the specific documents in one command.

These links are stored in the mainframe, so even if the original file is deleted, you’ll have a backup for most of the important files. Symbolic links help create invalid link pathways to store pieces of information as per the requirement of the user.

Due to the user-friendly features in Linux, even Microsoft is following it to create Symbolic Links. Symbolic links, also known as Soft links or Symlinks, are not unique to Linux but they are just like a Search option in Windows where one can search a specific file or directory in a disk by executing various commands.

Let’s look at how you can create file and folder links in Linux:

Generally, to create links use we use the ln command and the -s option to specify Symbolic links. This is the easiest way to ensure a flexible approach that allows experimenting with the language as much as possible. There is nothing hard in creating Symbolic links in Linux – you just need to follow one simple step.

The ln command in Linux creates links between source files and directories.

  • -s – the command for Symbolic Links.
  • [target file] – name of the existing file for which you are creating the link
  • [Symbolic filename] – name of the symbolic link.

Created links can be verified by directory listing using detailed list command:

However, if you do not specify the [Symbolic filename], the command will automatically create a new link in the existing directory.

Creating symbolic links for folders is not difficult either. The command used to create the folder symbolic link is:

For example, to link the /user/local/downloads/logo directory to /devisers folder, use the following command:

Once a Symbolic link is created and attached to the folder /devisers, it will lead to /user/local/downloads/logo. When the user changes directory – cd – to /devisers, the system will automatically change to the specific file and write it in the command directory.

Symbolic link options are called command line switches. Here are the most common ones and their descriptions:

Command Switch Description
–backup[=CONTROL] backup each existing destination file
-d, -F, –directory superuser is allowed to attempt hard link
-f, –force existing destination file is removed
-I, –interactive prompt before removing destination files
-L, –logical deference targets that are symbolic links
-n, –non-dereference symbolic links to directory are treated as files
-P, –physical make hard links directly to symbolic links
-r, –relative create symbolic links relative to link location
-s, –symbol make symbolic links instead of hard links
-S, –suffix=SUFFIX override usual backup suffix
-v, –verbose print name of each linked file

You can remove existing links attached to files or directories by the unlink or rm command. This is how you can do it with the unlink command:

Removing symbolic link using the rm command is similar to the unlink command which is as under:

Wrapping up

Remember, if the source is no longer in the current location, then you should delete the symbolic files to avoid creating duplicates, which might slow down your work.

Linux is a wonderful platform for creating an interactive and dynamic application, where you can experiment and innovate. A strong foundation is critical. Learn the basic of the language thoroughly to use it to its full potential. We hope this tutorial helped you improve your skills with another useful tool!

Edward is an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward’s goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.

Источник

linux-notes.org

Хотелось бы рассказать как можно создавать ссылки (симлинки) в ОС Unix/Linux. В своей теме «Создание ссылок (symlink) в Unix/Linux» я на готовом примере покажу как это делается. Существуют несколько видов ссылок, и я расскажу в чем разница между ними.

Читайте также:  Драйвер камеры windows 10 ноутбук

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

Жёсткой ссылкой — это структурная составляющая файла которая описывает его элемент каталога.

В этом подразделе, я расскажу какие бывают симлинки и в чем они отличаются.

Мягкая ссылка (Soft link):

  1. Мягкие ссылки используют различные номера инод чем основные файлы.
  2. Мягкие ссылки становится полезными, если исходный файл был удален.
  3. Мягкие ссылки могут быть созданы из каталогов.
  4. Мягкая ссылка может быть создана на пересечении файловых систем.

Для того чтобы создать симлинк в линукс используется следующая команда:

И так, я создал симлинк linux-notes.org.conf на на тот же файл но который будет расположен в другой директории. После создания симлинка, необходимо сменить права на него:

Для проверки номера иноды:

Я создал симлинк на файл, так же, можно создавать симлинка на целую папку, для этого используйте:

И так, я создал симлинк symlink-to-opt-dir на папку /opt/directory. После создания симлинка, необходимо сменить права на него:

Вот и все, очень просто, и полезно.

Для проверки номера иноды:

Чтобы удалить, используйте:

И аналогично для каталогов.

Если вы удалите мягкую ссылку (/home/captain/linux-notes.org-softlink.txt), то сам файл данных будет по-прежнему находится там же (/home/captain/linux-notes.org.txt). Тем не менее, если вы удалите /home/captain/linux-notes.org.txt, то /home/captain/linux-notes.org-softlink.txt станет сломанной ссылкой и данные будут потеряны.

Жесткие ссылки (Hard Links):

  1. Жесткие ссылки использует тот же номер иноды что и основные файлы.
  2. Нельзя создать жесткие ссылки на каталоги.
  3. Жесткие ссылки не могут быть созданы на пересечении файловых систем.
  4. Жесткие ссылки всегда относится к источнику, даже если они перемещаются или удаляется.

Чтобы создать «жесткую ссылку», используйте:

Проверяем номер иноды:

Оба файла имеют одинаковые иноды (одинаковое количество индексных дескрипторов). Если нужно удалить «жесткую ссылку», то используйте команду:

Если вы удалите жесткую ссылку, ваши данные будут там. Если вы удалите /home/captain/linux-notes.org.txt то файл будет по-прежнему доступен через жесткую ссылку

Жесткие ссылки (Hardlink) vs Мягкие ссылки (Softlink) в UNIX/Linux

  • Как я говорил ранее, жесткие ссылки не могут быть созданы для директорий.
  • Жесткие ссылки не могут использоваться на пересечении границ файловых систем ( Нельзя создать сылку /tmp и примонтированную на /tmp ко 2-му HDD который смонтирован на/harddisk2).
  • Символические ссылки (мягкие ссылки) ссылаются на символичный путь с указанием абстрактного расположение другого файла.
  • Жесткие ссылки, ссылаются к определенному местоположению физических данных.

На этом, моя тема «Создание ссылок (symlink) в Unix/Linux» завершена. Не сильно сложная тема, но очень полезная.

Источник

A symlink (also called a symbolic link) is a type of file in Linux that points to another file or a folder on your computer. Symlinks are similar to shortcuts in Windows.

Some people call symlinks «soft links» – a type of link in Linux/UNIX systems – as opposed to «hard links.»

Soft links are similar to shortcuts, and can point to another file or directory in any file system.

Hard links are also shortcuts for files and folders, but a hard link cannot be created for a folder or file in a different file system.

Let’s look at the steps involved in creating and removing a symlink. We’ll also see what broken links are, and how to delete them.

The syntax for creating a symlink is:

ln is the link command. The -s flag specifies that the link should be soft. -s can also be entered as -symbolic .

By default, ln command creates hard links. The next argument is path to the file (or folder) that you want to link. (That is, the file or folder you want to create a shortcut for.)

And the last argument is the path to link itself (the shortcut).

After running this command, you will be able to access the /home/james/transactions.txt with trans.txt . Any modification to trans.txt will also be reflected in the original file.

Note that this command above would create the link file trans.txt in your current directory. You can as well create a linked file in a folder link this:

There must be a directory already called «my-stuffs» in your current directory – if not the command will throw an error.

Similar to above, we’d use:

This would create a symlinked folder called ‘james’ which would contain the contents of /home/james . Any changes to this linked folder will also affect the original folder.

Before you’d want to remove a symlink, you may want to confirm that a file or folder is a symlink, so that you do not tamper with your files.

One way to do this is:

Running this command on your terminal will display the properties of the file. In the result, if the first character is a small letter L (‘l’), it means the file/folder is a symlink.

You’d also see an arrow (->) at the end indicating the file/folder the simlink is pointing to.

There are two methods to remove a symlink:

This deletes the symlink if the process is successful.

Even if the symlink is in the form of a folder, do not append ‘/’, because Linux will assume it’s a directory and unlink can’t delete directories.

As we’ve seen, a symlink is just another file or folder pointing to an original file or folder. To remove that relationship, you can remove the linked file.

Hence, the syntax is:

Note that trying to do rm james/ would result an error, because Linux will assume ‘james/’ is a directory, which would require other options like r and f . But that’s not what we want. A symlink may be a folder, but we are only concerned with the name.

The main benefit of rm over unlink is that you can remove multiple symlinks at once, like you can with files.

Broken links occur when the file or folder that a symlink points to changes path or is deleted.

For example, if ‘transactions.txt’ moves from /home/james to /home/james/personal , the ‘trans.txt’ link becomes broken. Every attempt to access to the file will result in a ‘No such file or directory’ error. This is because the link has no contents of its own.

When you discover broken links, you can easily delete the file. An easy way to find broken symlinks is:

This will list all broken symlinks in the james directory – from files to directories to sub-directories.

Passing the -delete option will delete them like so:

Wrapping up

Symbolic link are an interesting feature of Linux and UNIX systems.

You can create easily accessible symlinks to refer to a file or folder that would otherwise not be convenient to access. With some practice, you will understand how these work on an intuitive level, and they will make you much more efficient at managing file systems.

Читайте также:  Как удалить кэш оперативной памяти windows 10

Frontend Web Engineer and Technical Writer. I love teaching what I know. Javascript / ReactJS / NodeJS

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives and help pay for servers, services, and staff.

Источник

Linux zip folder | 16 practical Linux zip command examples

Table of Contents

Linux Zip Command Examples

In this tutorial I will share various Unix and Linux zip command examples and scenarios to understand how to zip a folder and how to create a zip file.

zip is a compression and file packaging utility for Unix, VMS, MSDOS, OS/2, Windows 9x/NT/XP, Minix, Atari, Macintosh, Amiga, and Acorn RISC OS.

Pre-requisite:

Before we zip a folder and create a zip file in Linux or Unix, we must install the zip and unzip utility.

Install zip

In some Linux and Unix variants, zip is installed by default with operating system. You can also manually install zip utility by using yum

Install unzip

Similarly to be able to unzip files and folders in Linux or Unix you will need unzip utility

1. How to zip a folder with multiple files Linux

In this Linux zip command example you will learn, how to zip a folder with multiple files or all files from the current working directory and store the archive at the same location. List the files which you wish to zip using ls command

Let’s take this Linux zip command example. Here we will zip multiple files or rather all the files from current working directory.

Verify the newly created zip file ( rpms.zip )

Now in the last zip command example we archived all the files present inside /tmp/files directory. Now I wish to zip all files except one or some selected files. In this case you must provided the name of the files which you wish to archive so zip will only consider those files for compression and archive.

So now our archive only contains two files which we provided as input and the archive was stored in the same path.

2. How to create a zip file by excluding some files

Use -x or —exclude to zip all files except some files to exclude files from being compressed and archived in Linux or Unix

Below Linux zip command example will show how to create a zip file with all files except some files.

To create zip a folder with all files except some files using a regex, here all file names starting with bc will be excluded

To create a zip folder by excluding multiple files

Similarly you can also zip all folders and exclude some directories using -r to zip directories

3. How to zip a folder by compressing directory and sub-directories

By default zip command will only compress files. if you attempt to compress directory, then you may get below output

As you see the stored content was 0%. So how to zip a folder or directory?

Use -r or —recurse-paths to zip a folder in Linux or Unix and compress directory structure recursively using Linux zip command example:

4. How to display zip archive content

We can use -dc or —display-counts to display running zip file count of entries. Check below Linux zip command example to list zip archive content without extracting.

5. How to zip a folder with password protection

You can zip a folder and also password protect the zip file using -e or —encrypt . With this argument you create a zip file with an encrypted password. Let us use this Linux zip command example to understand this better:

Now how to unzip files? If you try to unzip to directory, the zip file will prompt for password. Without password you will not be able to unzip to directory.

6. How to update or modify existing file in zip archive

You can use -f or —freshen to update or modify zip file content. With -f you replace (freshen) an existing entry in the zip archive only if it has been modified more recently than the version already in the zip file, unlike the update option (-u) this will not add files that are not already in the zip archive.

You can modify zip file content here.

Now add some more content to the existing file

7. How to add files to existing zip archive

How to add files to the existing zip archive, instead of creating a new zip archive. If this operation fails, zip attempts to restore the archive to its original state . If the restoration fails, the archive might become corrupted. This option is ignored when there’s no existing archive or when at least one zip archive member must be updated or deleted.

In my earlier Linux zip command example I had created a zip archive /tmp/test_archive.zip . Here we will will add new files to the same zip archive

8. How to list zip archive contents without extracting

You can also list zip archive contents without unzip to directory using -sf . For instance you have a requirement to check if a file exists in the archive so without unzip to directory you can list the zip file contents on the output and use additional regex and tools to grep the file you are looking for.

9. How to create a zip file without complete path (Store only the file name)

By default when we create a zip archive, it stores the relative path for the archived content. Lets take this Linux zip command example which stores the relative path of files:

Here list the content of test_archive , as you see the relative path is stored along with the filename

So to create a zip file in Linux without complete path and only store the filename in zip archive, we use -j or —junk-paths . This will create a zip archive without relative path of the files and store just the name of file (junk the path), and do not store directory names. For Example:

List and verify the zip archive content.

10. How to create a zip file and delete original files after archiving

  • By default when you create a zip file, it leaves the original files and folders after creating archive,
  • But you can also make zip delete original files after archiving is complete.
  • Instead of copy, Move the specified files into the zip archive
  • Actually, this deletes the original target directories/files after making the specified zip archive.
  • If a directory becomes empty after removal of the files, the directory is also removed.
  • No deletions are done until zip has created the archive without error .
Читайте также:  Exporting windows event logs

This is useful for conserving disk space, but is potentially dangerous so it is recommended to use it in combination with -T to test the archive before you make zip delete original files after archiving. In this we create a zip archive, and then delete the original files are we zip the folder.

After you zip a folder, verify the content stored under /tmp/files . So as expected the original files are deleted from the source location after archiving.

Similarly to store the entire content of /tmp/files including the source directory use -r directive

As expected our source directory is also deleted after archiving

11. How to zip a folder with higher compression level

When we zip a folder, the default zip compression level is -6 . zip command supports compression level from 3 where 0 means no compression and -9 means highest (maximum) compression. We will perform basic compression and monitor the time difference

With the default compression level, when we create a zip folder, the compressing of 1668 rpms the zip tool took

The original size of the source location was

which after compression is 842M so we saved

We increase the compression level to -9 and create a zip folder which is considered as the highest or maximum compression level.

Now with higher level of compression, zip took additional 3 seconds to complete the compression but we only save 1MB overall in our archive so the advantage was not very high compared to the time we invested.

12. How to copy files between two zip archives

You can also copy files from one zip archive to another using -U or —copy-entries argument without extracting.

Also requires the —out option to specify a different output file than the input archive.

Here in this Linux zip command example we copy files between two zip archives, I have an input archive with below content

I will copy one of the rpm to another new archive

Verify the content of the output_archive

If no input files appear on the command line and —out is used, copy mode is assumed:

13. Linux zip directory and remove files from zip archive

In Linux zip directory and using -d or —delete directive you can delete or remove files from zip archive.

Let us take this Linux zip command example. Here I have a Linux zip archive with below content

So to remove files from zip archive , I will remove two files from the existing zip archive without unzip to directory

Verify the content of the archive

14. Linux zip folder and preserve symbolic links

For UNIX and VMS (V8.3 and later) use -y or —symlinks , create a zip folder and store and preserve symbolic links in zip archive.

This can avoid multiple copies of files being included in the archive as zip re curses the directory trees and accesses files directly and by links.

Let’s take this Linux zip command example. Here I have created a dummy file inside my root’s home folder and added some content.

Create a symlink to this dummy file

Verify the symlink

Next create a zip folder including symlink using -y or —symlinks argument to make zip preserve symbolic links

I will create a dummy location to extract the archive and verify the symlink

Unzip to directory using unzip command

Unzip to directory the newly created archive using unzip to make sure zip was able to preserve and store symbolic links

So with -y we make zip preserve symbolic links

Next verify the symlink content.

15. How to create a zip file and compress with bzip2

You can create a zip file with bzip2 compression. Set the default compression method using -Z or —compression-method . Currently the main methods supported by zip are store and deflate. Compression method can be set to:

  • store — Setting the compression method to store forces zip to store entries with no compression. This is generally faster than compressing entries, but results in no space savings. This is the same as using -0 (compression level zero).
  • deflate — This is the default method for zip. If zip determines that storing is better than deflation, the entry will be stored instead.
  • bzip2 — If bzip2 support is compiled in, this compression method also becomes available.

Extract content using unzip command

Extract the content using unzip to directory

16. How to zip a folder and later split zip archive

  • How to zip a folder and enable creating a split zip archive and set the split size using -s or —split-size .
  • A split zip archive in Linux and Unix is an archive that could be split over many files.
  • As the zip archive is created, if the size of the archive reaches the specified split size, that split is closed and the next split opened.
  • In general all splits but the last will be the split size and the last will be whatever is left .
  • If the entire archive is smaller than the split size a single-file archive is created.
  • Split size is a number optionally followed by a multiplier.
  • Currently the number must be an integer.
  • The multiplier can currently be one of k (kilobytes), m (megabytes), g (gigabytes), or t (terabytes).
  • As 64k is the minimum split size, numbers without multipliers default to megabytes

Let’s use this Linux zip command example to create a zip folder with split enable. I have Packages directory with files having size of 902MB. Here I will create zip archive

The last file as you see is of 36MB while all the other archive is of 200MB which we had used as the split size

Lastly I hope the steps from the article to compress and archive using zip command and cover scenarios life zip multiple files and folders, zip all files except some files and folders, compress directory and preserve symbolic links, remove files from zip archive, zip delete original files in Linux and Unix was helpful. So, let me know your suggestions and feedback using the comment section.

References:

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

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