1

There is a file name as pkg_list

a-1.2b-1.tar.gz
c-2.5b-1.tar.gz
a xx-1.4.txz
a$xx-1.4.txz
中文-3.txz
xx-3.2-2.tar.gz
xxy-1.3.tar.gz

My bash function can input package name like 'xx'

pkg_find() { # <pkg_name> as $1
  grep "^$1-[0-9]*" pkg_list
}
pkg_find xx # wish it return xx-3.2-2.tar.gz

I know I can not pass $1 directly into pkg_find, what's the correct method?

[SOLVED] In this case, because $1 is enclosed by double quote, I found even regex meta chars could pass as parameter.

Daniel YC Lin
  • 15,050
  • 18
  • 63
  • 96
  • Do you want the argument to the script i.e `$ ./script.sh xx` to be passed on to the function? then you need `pkg_find $1`. – jgr Jan 09 '13 at 10:00

3 Answers3

2

What you're doing looks right to me.

What isn't working?

I tried the code in your question, and pkg_find xx displays ‘xx-3.2-2.tar.gz’ — which you say is the output you were hoping for.

Smylers
  • 1,673
  • 14
  • 18
1

You can pass $1 directly to pkg_find

pkg_find() { # <pkg_name> as $1
  grep "^$1-[0-9]*" pkg_list
}
pkg_find "$1"

In the main body, $1, $2, .. are the script arguments, you get from the command line or another calling script. In a shell function they refer to the function arguments.

When you call this on the command line

sh pkg_find.sh xx

you will get

xx-3.2-2.tar.gz

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
0

Your code and your question seem to me to ask for different things, you want to either/both of:

$1, $2 etc at the top-level of a script are the script parameters; within a function they are set to the function parameters, or unset if there are no parameters.

Community
  • 1
  • 1
mr.spuratic
  • 9,767
  • 3
  • 34
  • 24