I am learning the shell commands and came across the short tags eg.[0-9],[[:digit:]] etc.. As a proof of concept i tried deleting all the files with the rm command(i know its not a good practise but i am trying to understand how things work),like this
rm [0-9].txt
there were two files in the directory 0.txt and 9.txt and it deleted the files 0.txt and 9.txt .I guessed that the expression [0-9] is expanded and then read as 0.txt 1.txt 2.txt …. However when you try only
rm 5.txt,and the file does not exist, an error is thrown..
someone please tell me how the shorthand commands work when used with rm or ls.
Best Answer
This is called globbing (link to bash documentation, but this is not specific to bash).
When you ran
rm [0-9].txt
, the shell expanded[0-9].txt
to the list of files present in the directory that matched that pattern. Then that list is passed as an argument torm
(each file as a separate argument).So no, the shell didn't expand it to
0.txt 1.txt ... 9.txt
, it looks at the files that matched.Why you run just
rm 5.txt
, there is no glob pattern to expand, so the argument is passed as-is torm
, which notices that the file doesn't exist and complains.Try something else: same command
rm [0-9].txt
, but in a directory that doesn't have any file that matches the pattern. You'll noticerm
complains again, but this time it will say:This is what happens (by default anyway) if a glob pattern doesn't match anything: the shell doesn't expand it and leaves it untouched.
POSIX reference for this sort of pattern matching: Pattern Matching Notation.