How to pass * as part of argument string to script?

Bo Berglund bo.berglund at gmail.com
Wed Aug 25 07:24:37 UTC 2021


I am writing a script to prune a directory of certain files and it works fine
provided the pattern to search for is entered directly in the script.
But when I try to set it as a parameter on the command line the pattern seems to
be expanded before being read by the script...
How can I avoid this?

Here is how I read the template argument:

if [ -z "$2" ]; then
  template="202*.mp4" #Default file template for listing
else
  template="$2"
fi

And here is how template is used:
cntall=`find . -maxdepth 1 -name "202*.mp4" -printf '.' | wc -m`
#cntall=`find . -maxdepth 1 -name "${template}" -printf '.' | wc -m`

As shown it works OK using the first line.

But if I move the comment to the line above and enter the string 202*.mp4 as
argument 2 on the command line then the script is no longer working.

It turns out that $template is set to the first file name *matching* the pattern
with the entered wildcard *!

So if I have these files:
2021-08-12_myvideo.mp4
2021-08-13_myvideo.mp4
2021-08-14_myvideo.mp4
2021-08-15_myvideo.mp4
2021-08-16_myvideo.mp4
2021-08-17_myvideo.mp4

I expect cntall to be set to 6 but in fact it will be 1 because inside the
script the entered string 202*.mp4 intended as $template is expanded to be
2021-08-12_myvideo.mp4, which when used as $template always will return 1 from
the call above...

How can I use a template input with the script without Ubuntu expanding my input
before it gets to the script?


-- 
Bo Berglund
Developer in Sweden





More information about the ubuntu-users mailing list