Implementing globbing in a prototype shell

I use the linux shell for a weekend job, and I am having trouble implementing wilcard matching as a function in the shell. As we all know, shells are a complete language in themselves, for example. bash, ksh, etc. I do not need to implement functions such as control structures, tasks, etc. But how to implement * ?

A quick analysis gives the following result:

 echo * 

lists all files in the current directory. Is this the only logical manifestation of the shell? I mean, not considering the language-specific bash functions, is that what the shell does inside? Replace * with all files in the current directory matching the pattern?

I also heard about Perl Compatible Regular Expression, but it seems difficult to use a third-party library.

Any suggestions, links, etc.? I will also try to look at the source code for bash.

+4
source share
3 answers

Yes, this is what the shell does. It will replace the '*' characters with all the file and folder names in cwd . These are actually very simple regular expressions that support only '?' and '*' and corresponding to the names of files and folders in cwd . Note that backward-resettable \* and '*' enclosed between single or double quotation marks ' or " not replaced (backslash and quotation marks are removed before passing to the executable command).

+2
source

This is called "globbing", and the function that does this is called the same: glob (3)

+3
source

If you need more control than glob , the standard fnmatch function only performs glob matching.

Note that shells also decompose words (for example, "~" β†’ "/home/user" ), which should be done before the glob extension if you do a file name manually. (Or use wordexp .)

+1
source

Source: https://habr.com/ru/post/1336962/


All Articles