Monday, June 3, 2013

This article is part of a unix shell scripting tutorial. We must know liitle things like below while writing shell scripts in linux.

Sometimes, we are not able to delete files from directory in Linux.
There are many reasons due to which we can’t delete that files as I have given
example. Below filename which I have mentioned, its name starts with – that’s
why we can’t delete it directly.

You can see just list of files before issue.

root@hello:~/test/hello#
ls

a.sh a.txt
file2 module test.html
-unable.txt

root@hello:~/test/hello#

I am creating file which will not delete by normal rm
command.

root@hello:~/test/hello#
cat > -unable.txt

Hello

How are you

root@hello:~/test/hello#

root@hello:~/test/hello#
ls

a.sh a.txt
file2 module test.html
-unable.txt

rm command facing the issue while deleting that file. We are
getting errors.

root@hello:~/test/hello#
rm "-unable.txt"

rm: invalid
option -- 'u'

Try `rm
./-unable.txt' to remove the file `-unable.txt'.

Try `rm --help'
for more information.

root@hello:~/test/hello#
rm -rf "-unable.txt"

rm: invalid
option -- 'u'

Try `rm
./-unable.txt' to remove the file `-unable.txt'.

Try `rm --help'
for more information.

root@hello:~/test/hello#

There is only one way to resolve this issue is that check
inode for that file by ls command with –i option. It will give us inode number
in first column for that file.

root@hello:~/test/hello#
ls -lrti

total 100

5770436
-rw-r--r-- 1 root root 80878 2012-11-03 18:00 test.html

5770345
-rw-r--r-- 1 root root 45 2012-11-05
21:59 file2

5770346
drwxr-xr-x 3 root root 4096 2012-11-05
22:35 module

5770437
-rw-r--r-- 1 root root 11 2012-11-09
16:50 a.txt

5770440
-rw-r--r-- 1 root root 128 2012-11-09
16:50 a.sh

5770079
-rw-r--r-- 1 root root 19 2013-06-03
22:04 -unable.txt

root@hello:~/test/hello#

Use above inode number in find command to search file and
delete it by using rm command inside the –exec option. Finally, we have
successfully deleted that file.

root@hello:~/test/hello#
find . -inum 5770079 -exec rm -rf {} \;

root@hello:~/test/hello#
ls

a.sh a.txt
file2 module test.html

root@hello:~/test/hello#

This case not belong to only the file
names whose name starts with – character but also in some other cases like- if
file not created properly then we can’t delete it etc. If you are not able to
delete files then just use this trick, it will be helpful for all cases.