Register
It is currently Thu Apr 24, 2014 7:29 pm

A query RE: string operator syntax


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Fri Sep 24, 2010 6:49 am   

Joined: Fri Sep 24, 2010 6:26 am
Posts: 1
Apologies for the utter triviality of this question all, but we all have to start somewhere!

Anyway, I'm in the process of self-teaching basic (bash) scripting as I'm bound to need to know it eventually. Currently, I'm just reading/working through "Learning the bash shell" (Newham & Bosenblatt) and working through the exercises which, to be fair, aren't exactly difficult. However, I'm puzzled by one particular facet of one of the tasks, specifically 'string operators'....

The task is simple, recursively sort a text file and print the top X results. This is OK and makes perfect sense. I'm trying to take it one step further and add a user variable to optionally print a header. This is pretty easily accomplished via:

Code:
header=$1
file=$2
file=${file:?"input file not specified"}
number=$3

echo -e -n ${header:+"albums      artist\n"}

sort -nr $file | head -${number:=10}


but this prints the headers with anything in position $1. How would I go about only printing the header if the user defines "-h" in $1? It's a pretty trivial problem to be fair, but its been bugging me for a while now. Of the top of my head I'm guessing theres a way to have a variable only defined (i.e. $header in this case) when theres a particular string input (i.e. -h) in $1, but I'm not entirely sure on the syntax to accomplish it. Note that I'm aware I could probably do this with an if statement or something, but I'd like to do it via a string operator.

Cheers.


Top
 Profile  
 PostPosted: Sun Sep 26, 2010 12:36 am   
User avatar

Joined: Sun Jun 27, 2010 12:57 am
Posts: 192
Jasong wrote:
How would I go about only printing the header if the user defines "-h" in $1?


The easy way:
Code:
if [ "$1" == "-h" ]; then
  echo "albums      artist"
fi


But the right way would be to use getopt to parse your options, instead of 'hard' coding them as $1, $2 and $3


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 7 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP