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=$1file=$2file=${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.

Who is online

Users browsing this forum: No registered users and 1 guest

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