Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I wanted to create a file named test. Accidentally I run mkdir test instead of touch test.

Is it possible to convert test directory in a file named test?

What about converting a file named test into a directory with the same name?

share|improve this question
5  
rm -f test && touch test except this, I really don't know –  Kiwy Mar 4 at 14:23
    
@Kiwy Yeah, but I am imagining a built-in command that is designed to do this task. –  Ionică Bizău Mar 4 at 14:24
add comment

3 Answers 3

up vote 7 down vote accepted

This isn't possible for any Unix or Linux I've ever touched.

Under some older Unixes, directories are files, specially marked, but still files. You used to be able to read a directory with cat under SunOS, for example. A lot of modern filesystems might have directories as B+ trees, or some other on-disk data structure. So turning a file into a directory or vice versa would always require a delete and a re-creation with the same name.

share|improve this answer
    
Interesting. If nobody comes with a solution I will mark this answer. :-) –  Ionică Bizău Mar 4 at 14:54
add comment

No there is no such command because there would be absolutely no point in it. Your question is like asking for a way to transform a box into a flat rectangle. What would you do with the things in the box (directory)? How would the rectangle correspond to the box it came from?

Files and directories serve completely different functions. While a directory is indeed a file in *nix systems, that only applies to the internals of the system and not to what you, the user, see. So, converting a file to a directory, or vice versa, will always involve deleting the file and creating the directory. The best you could hope for would be to use the same inode but again, not much point in that.

share|improve this answer
add comment

Create a function to do what you want. (bash or other Bourne/POSIX like shell assumed)

$ dir2file() { rmdir -- "$1" && touch -- "$1";}
$ mkdir adir
$ dir2file adir
$ ls -l adir
-rw-r--r-- 1 xtian xtian 0 2014-03-04 14:59 adir
$ 

I deliberately use rmdir which will fail if adir is not a directory or not empty (no -f to force). touch will run only if rmdir succeeds.

You could put the function definition in your shell customisation file (.bashrc for bash).

share|improve this answer
    
@Stephane Chazelas What does the -- do ? –  X Tian Mar 4 at 18:31
2  
the -- marks the end of the flags so rmdir and touch know anything past it is a filename, even if it starts with -. –  Kevin Mar 4 at 18:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.