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

Karl Auer kauer at biplane.com.au
Wed Aug 25 08:15:45 UTC 2021


On Wed, 2021-08-25 at 09:24 +0200, Bo Berglund wrote:
> 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?

Ah Bo - welcome to the wonderful and intriguing world of globbing,
quoting and escape characters!

The BEST way is to allow the shell to do your work for you, i.e.,
expect all the filenames on the command line. That way you can say

   ./myscript 202*.mp4

... and the script will process all the matching files. To do this,
investigate the "shift" command, which moves all the arguments one to
the left, discarding the first.

If you MUST pass the pattern in to the script so the scripts can use
it, you will need to quote it on the command line:

   ./myscript "202*.mp4"

If you need to pass it around inside the script, keep it quoted.

Here is a little test script you can play with:

   #!/bin/sh
   GLOB="$1"

   echo "~~ echo first parameter ~~~~~~~~~~~~~~~~~"
   echo "$GLOB"

   echo "~~ use first parameter in find ~~~~~~~~~~"
   find . -name "$GLOB" -print

   echo "~~ move through parameters with shift ~~~"
   COUNT=0
   while [ $# -gt 0 ] ; do
      echo "$1"
      COUNT=`expr $COUNT + 1`
      shift
   done

   echo "Counted the hard way: $COUNT"

Try passing arguments quoted, unquoted, with escape characters etc to
see what the various methods do.

Regards, K.

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Karl Auer (kauer at biplane.com.au)
http://www.biplane.com.au/kauer

GPG fingerprint: 61A0 99A9 8823 3A75 871E 5D90 BADB B237 260C 9C58
Old fingerprint: 2561 E9EC D868 E73C 8AF1 49CF EE50 4B1D CCA1 5170







More information about the ubuntu-users mailing list