metacharacter in function
For the final assignment of my UNIX class, we have to create a shell script.
I have written mine, but there is one thing that I can't figure out.
If I take the lastname variable out, and in the grepit function put $1 as the variable, it will not work. Why is that? Can a function not use a metacharacter like that?
EDIT: I probably should tell you a little more about the script. At the prompt you type rolldex lastname. If you type two last names then you get an error, if you don't type any names, you get an error. If you do enter one lastname then it check to see if that name exists in the file telephone.numbers, and if it does, it prints the first name, lastname, area code, prefix, and suffix, in that order with a space in between values.
Abhishek Reddy posted this at 09:44 — 30th November 2006.
He has: 3,348 posts
Joined: Jul 2001
There's a somewhat silly reason why you can't do that, and a good reason why you shouldn't.
[incode]$1[/incode] basically means the first argument. At the top level it's, the first argument to the script; but inside a function it's the first argument to the function. To read the script's first argument from a function, either copy the script's first argument to another variable -- which you have -- or pass it as an argument to your function.
I would use another variable (like [incode]lastname[/incode]), as it's better style and more maintainable. The program logic is separated from the its interface. It's also more readable.
teammatt3 posted this at 22:43 — 30th November 2006.
He has: 2,102 posts
Joined: Sep 2003
Ok, that makes sense. Knowing that, I used it in my script. I made a new function called cutit and...well, I don't want to explain it. Have a look yourself . That is my final script (maybe ). I think I got everything working the way it's supposed to.
Thanks again for the help, we never covered functions in the class (not in the book either).
EDIT: Changed it again, combined grep and cut together in a function. Man, I love scripting.
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.