How to pass a regular expression as a parameter to a shell script?
I need to write a shell script, which will take parameters and give them to unix commands. And I’d like to use regular expressions there. Is this possible at all?
Or reformulation – how to write the script equivalent to “cp” command, using only this command?
I’m trying to make a file “mycp”
#!/bin/bash -fx
cp $2 $1
and call it by
mycp myDir "*sh"
and want it to do the same as “cp *sh myDir”.
But resulting bash interpretation is:
+ cp '*sh' myDir
cp: *sh: No such file or directory
Revised question
In that case, you still need
eval, but you’d write:You’re running into problems because you have specified the
-foption.man bashsays (in part):Remove the
ffrom the ‘shebang’ (first) line of the script.Original question
Given that you want
mycp "*sh*" aato do shell expansion on the argument, you’ll probably end up usingevalin your script:However, the use of
evalis dangerous; it can lead to unexpected side-effects. The use of"$@"is important; it preserves the number of arguments and spaces in them. Unfortunately, usingevalthen undoes that, but we can’t have everything — or not easily.For quite a long time (say 1987* to 1999), I used this script as a cover for
cp:It uses a very simple C program called
la(for ‘last argument’) to get the last argument and checks whether the given last argument is a directory. More than 99% of the time, if I typed (by accident) ‘cp /some/where/sh‘ rather thancp /some/where/*sh* ., the second was what I meant, and the script fixed things. I haven’t used it for quite some time; it may have been in the last millennium, but was probably sometime earlier in this one that I gave up using it.* Although the version string says ‘1997’, the code is identical to the 1987 version. Version 1.1 and 1.2 were under SCCS and used different SCCS ID strings; the conversion to RCS made them identical. Version 1.3 reinstated the
@(#)identifier string used by the SCCSwhatcommand to the RCS version handling. So, the script is ancient — 1987, really.