Linux Commands: Working with Directories


There is another batch of commands suited to working with directory files (directories being just another type of file):

pwd

Print Working Directory.

cd

Change to a new Directory.

mkdir

MaKe or create a new DIRectory.

mv

MoVe directories, or, like files, rename them.

rmdir

ReMove or delete DIRectories.


One way to create a complicated directory structure is to use the mkdir command to create each and every directory:

 mkdir /dir1 mkdir /dir1/sub_dir mkdir /dir1/sub_dir/yetanotherdir 

What you could do instead is save yourself a few keystrokes and use the -p flag. This tells mkdir to create any parent directories that might not already exist. If you happen to like a lot of verbiage from your system, you could also add the --verbose flag for good measure:

 mkdir  p /dir/sub_dir/yetanotherdir 

To rename or move a directory, the format is the same as you used with a file or group of files. Use the mv command:

 mv path_to_dir new_path_to_dir 

Removing a directory can be just a bit more challenging. The command rmdir seems simple enough. In fact, removing this directory was no problem:

 $ rmdir trivia_dir 

Removing this one, however, gave me this error:

 $ rmdir junk_dir rmdir: junk_dir: Directory not empty 

You can only use rmdir to remove an empty directory. There is a -p option (as in parents) that enables you to remove a directory structure. For instance, you could remove a couple of levels like this:

 rmdir  p junk_dir/level1/level2/level3 

Warning

Beware the rm rf * command. Better yet, never use it. If you must delete an entire directory structure, change directory to the one above it and explicitly remove the directory. This is also the first and best reason to do as much of your work as possible as a normal user and not as root. Because root is all powerful, it is quite capable of completely destroying your system. Imagine that you are in the top-level directory (/) instead of/home/myname/junkdir when you initiate that recursive delete. It is far too easy to make this kind of mistake. Beware.


All the directories from junk_dir on down will be removed, but only if they are empty of files. A better approach is to use the rm command with the -r, or recursive, option. Unless you are deleting only a couple of files or directories, you will want to use the -f option as well:

 $ rm  rf junk_dir 



Moving to Linux(c) Kiss the Blue Screen of Death Goodbye!
Moving to Linux: Kiss the Blue Screen of Death Goodbye!
ISBN: 0321159985
EAN: 2147483647
Year: 2003
Pages: 247

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net