1. Manipulating files and directories
To work with files and directories we can use these commands:
cp- Copy files and directoriesmv- Move/rename files and directoriesmkdir- Create directoriesrm- Remove files and directoriesln- Create hard and symbolic links
Let's use them in some examples.
-
Creating directories:
cdmkdir playgroundcd playgroundmkdir dir1 dir2ls -l -
Copying files:
cp /etc/passwd .ls -lNotice that
.is the current working directory.cp -v /etc/passwd .The option
-vmakes the command verbose.cp -i /etc/passwd .The option
-imakes the command interactive. This means that it asks you first, before doing any potentially destructive actions. Pressyornto continue. -
Moving and renaming files:
mv passwd funls -lmv fun dir1ls -lls -l dir1mv dir1/fun dir2ls -l dir1ls -l dir2mv dir2/fun .treemv fun dir1mv dir1 dir2treels -l dir2/dir1mv dir2/dir1 .mv dir1/fun .tree -
Creating hard links:
ln fun fun-hardln fun dir1/fun-hardln fun dir2/fun-hardls -lRNotice that the second field in the listing of
funandfun-hardis4, which shows the number of the links for the file. Hard links are like different names for the same file content.To make sure that all four of them are the same file, let's try the option
-i:ls -lRiYou may notice that the number on the first column is the same for all the files. This is called the inode number of a file, and can be thought as the address where the file is located. Since it is the same for all the files, this shows that they are actually the same file.
-
Creating symbolic links:
ln -s fun fun-symls -lSymbolic links are a special type of file that contains a text pointer to the target file or directory. They were created to overcome two disadvantages of hard links:
- hard links cannot span physical devices
- hard links cannot reference directories, only files
ln -s ../fun dir1/fun-symln -s ../fun dir2/fun-symtreeThese two examples might seem a bit difficult to understand what is going on. But remember that when we create a symbolic link, we are creating a text description of where the target file is, relative to the symbolic link.
We can also use absolute file names when creating symbolic links:
ln -sf /home/user1/playground/fun dir1/fun-symls -l dir1/However, in most cases, using relative pathnames is more desirable, because it allows a directory tree containing symbolic links and their referenced files to be renamed and/or moved without breaking the links.
In addition to regular files, symbolic links can also reference directories:
ln -s dir1 dir1-symls -l -
Removing files and directories.
Let's clean up the playground a little bit. First let's delete one of the hard links:
rm fun-hardls -lNotice that the link count for
funis reduced from 4 to 3 (as indicated in the second field of the directory listing).rm -i funPress
yls -lless fun-symThe symbolic link now is broken.
rm fun-sym dir1-symls -lWhen we remove a symbolic link the target is not touched.
rm -r dir1/cd ..rm -rf playground/