BASH - set specific user variable via string operators

Apologies for the utter triviality of this question, but we all have to start somewhere! I've also tried searching but this question is pretty vague so I didn't (a) really know what to search for or (b) get many relevant hits to what I did search for.

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:

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 if anything is 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. :slight_smile:

With only 1 option, there's no need of getopts (which is a powerful feature of bash), so you can proceed this way:
if [ "$1" = "-h" ]
then
header=$2
shift 2 # puts the 3d param in $1 and the 4th in $2
fi
file=${1:?"input file not specified"}
echo -e -n ${header:+"albums artist\n"}
sort -nr $file | head -${2:=10}

I simplified it a bit, avoiding intermediate variable names.