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 files, and 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 


You could 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 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 an 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 of the rm rf * command. Better yet, never use it. If you must delete an entire directory structure, change the 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 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 are 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 want to use the -f option as well.

$ rm rf junk_dir 





Moving to Ubuntu Linux
Moving to Ubuntu Linux
ISBN: 032142722X
EAN: 2147483647
Year: 2004
Pages: 201

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