[ale] Bash parameter expansions
Alex Carver
agcarver+ale at acarver.net
Sun Feb 13 17:50:56 EST 2022
I'm putting a tiny utility script together to make it faster for me to
update ipset lists and add them to a restore file in one shot but I've
run into a slight hiccup with what I wanted to accomplish.
So in the ideal case the script is called like this:
addip.sh listname cidr [multiple word comment]
The key is the multiple word comment which I wanted to be lazy and not
have to type in quotation marks around it. No problem for that, I just
gather up anything on the command line after the second parameter:
comment="${*:3}"
The problem is when I'm trying to pass this to both ipset and to
concatenate to the end of a file. The call to ipset would be:
ipset add ${1} ${2} {$comment:+comment} ${comment}
and appending to file would be:
echo add ${1} ${2} {$comment:+comment}
${comment:+\"}${comment}${comment:+\"} >> savefile
The ipset command uses the alternate text expansion to put the literal
word 'comment' on the command line if $comment is not empty. The echo
command does something similar and also uses that same method to wrap
the text in double quotes if it's not null (this is to avoid having
'comment ""' in the save line).
The problem is the comment variable on the ipset line. If I call my
script with no comments (addip.sh list ip) then it executes ipset just
fine and the file gets a copy of the entry with no comment added.
But if I call it with the addition of a comment, ipset sees an extra
parameter at the end of it's command line and complains with an unknown
argument error:
addip.sh test 100.0.0.0/32 This is my comment
ipset: Unknown argument: 'is'
Ok, so normally I would think to do something like this:
ipset add ${1} ${2} {$comment:+comment} "${comment}"
But that then breaks the condition where no comment is desired. In this
case I get an unknown argument error again but for an empty one:
addip.sh test 100.0.0.0/32
ipset: Unknown argument: ''
I was trying to set up the script to have ipset called in only one place
instead of calling it twice using an if/else block but I can't quite
figure out how to get the parameter expansion to work for both cases.
Plus whatever I do has to also satisfy the echo statement to produce one
of these two strings to append to the file depending whether there's
comments or not:
add test 10.0.0.0/32
add test 10.0.0.0/32 comment "This is my comment"
Thoughts?
More information about the Ale
mailing list