LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   getopts - how to read in a regular expression without interpretation (https://www.linuxquestions.org/questions/linux-newbie-8/getopts-how-to-read-in-a-regular-expression-without-interpretation-877063/)

lynne007 04-25-2011 09:26 PM

getopts - how to read in a regular expression without interpretation
 
I am modifying a script that uses a getopts to read in options. One of the options allows to user to narrow down the files searched. The user can specify a pattern like *.c* for all files of type .c and .cpp.

the script xxx is called like this:

xxx -n *.c*

in this logic:
while getopts ":l:n:d:s" opt; do
case $opt in
l ) LIB=$OPTARG ;;
d ) SEARCH_DIRS=$OPTARG ;;
n ) NAME="$OPTARG" ;;
s ) SHOW="" ;;
esac
done
if I say NAME='$OPTARG', then I get the literal '$OPTARG'. If I put "$OPTARG", in the script, when option n is saved in a variable NAME, instead of NAME being equal to '*.c*', NAME is equal to the first file with a type starting with c (*.c*) found in the directory from which I am executing xxx. It is like it is interpreting the regular expression before saving it in variable NAME.

How can I the literal '*.c*' to be stored in NAME?

thanks.

Berhanie 04-25-2011 09:35 PM

you need to quote the value (note the quotes):
Code:

xxx -n '*.c*'

lynne007 04-25-2011 10:57 PM

Quote:

Originally Posted by Berhanie (Post 4336260)
you need to quote the value (note the quotes):
Code:

xxx -n '*.c*'

so.. there is no way to specify that the option is not to be interpreted? The user has to quote any regular expression that is used as input?

Berhanie 04-25-2011 11:12 PM

Quote:

there is no way to specify that the option is not to be interpreted?
no, because it's the shell that expands it before calling the script.

lynne007 04-25-2011 11:37 PM

Quote:

Originally Posted by Berhanie (Post 4336324)
no, because it's the shell that expands it before calling the script.

ok. Thanks.

David the H. 04-26-2011 02:07 AM

Read up on how bash quoting and shell expansion work here:

http://tldp.org/LDP/Bash-Beginners-G...ect_01_04.html
http://tldp.org/LDP/Bash-Beginners-G...ect_03_03.html
http://tldp.org/LDP/Bash-Beginners-G...ect_03_04.html

In short, when the shell reads an input line, it first looks for all the characters and expressions on the line that have reserved shell meanings. It then processes these, expanding and substituting them with the actual contents they represent. Then finally it executes the expanded command(s).

Quoting is what you use to protect strings from this expansion process, allowing them to be passed to the command you're running as-is.


By the way, please use [code][/code] tags around your code, to preserve formatting and to improve readability.


All times are GMT -5. The time now is 08:08 PM.