Linux / UNIX : Move File Starting With A Hyphen
In Linux sometime we have some strange and silly mistake while creating files and directories which make Linux command prompt difficult to work.Today we will talk about one of issues that i faced recently.
One of client pinged me regarding one issue that he is not able to work with some of Linux commands, some strange output comes instead of usual output, while seeing it closely i noticed that his team created some files start with hyphen or dashes (–) which causes difficult for some commands.
So Question is, how to deal with files start with hyphen or dashes like (–ostype). In short if we have file name start with like this we faced some strange output while running some commands in this directory like du command. We need to see how we can rid these files like either delete them or move to some other name so which can easily handle with any command
File contain Hyphen
In below command we can see that we have one file name –ostype which causes du command not able to calculate size of any files contain in same directory. SO we have to see how we can deal with this file
[root@srv1 etc]# ls -l | grep type -rw-r--r-- 1 root root 43591 Sep 23 2011 mime.types -rw-r--r-- 1 root root 0 May 3 07:54 --ostype [root@srv1 etc]# du -sh * du: unrecognized option '--ostype' Try `du --help' for more information.
How to work with hyphen files
Although its not causing issues for many command or we can also escape this file name with some simple bash trick. Let’s first see how we can come up with such solution which make it work as usual with same file name.
[root@srv1 etc]# du -sh -- --ostype 0 --ostype
In above commands we can see we are able to overcome this file contain hyphen in its name and with it we can able to run du command as it work with any other file or directory.
So trick is bash has this option for “– signals the end of options and disables further option processing”. This way we can able to escape these extra hyphen, so will not impact command with it.
We can also move or remove these files through below way, in case someone accidentally create these files .
[root@srv1 etc]# rm -rf -- --ostype [root@srv1 etc]# touch -- --ostype [root@srv1 etc]# mv -- --ostype ostype [root@srv1 etc]# ls -l | grep ostype -rw-r--r-- 1 root root 0 May 3 08:06 ostype
SO with above, now we know how we can create files with hyphen and how we can deal with them with some easy bash tricks.