I'm trying to shorten a bash solution to a Code Golf challenge, which requires an output of true
or false
. I've managed to condense the key piece of the code down to a substring check, to determine if the provided argument, $1
, is a substring of a particular hard-coded fixed string, of the form:
[[ FIXEDSTRING = *$1* ]]&&echo true||echo false
# And a minor improvement to shave a character on the test:
[[ FIXEDSTRING =~ $1 ]]&&echo true||echo false
My question is, is there some clever way to shorten this, either in general, or for the specific case of converting success to true
and failure to false
?
In a language like Python, I'd use:
# Shortest solution without imports I know of
str(sys.argv[1]in"FIXEDSTRING").lower() # Also feels a little long, kinda
# curious if there is a better way
# Shorter when json is already imported for some other purpose, saves a character (more if
# json aliased or dumps denamespaced via from json import*):
json.dumps(sys.argv[1]in"FIXEDSTRING")
for the specific case of "success is true
, failure is false
", and one of:
# When string lengths close enough for stepped slicing to work, only 3 characters longer
# than the true/false specific solution
"ftarlusee"[sys.argv[1]in"FIXEDSTRING"::2]
# When string lengths aren't compatible for stepped slicing,
("false","true")[sys.argv[1]in"FIXEDSTRING"]
when I need to select between arbitrary strings, not just true
/false
.
But AFAICT:
bash
has no concept of converting from success/failure to a specific string (without relying onif
/then
/fi
,case
/esac
or&&
/||
and manually runningecho
with a literal string for each string option)bash
arrays can't be used "anonymously", and the array indexing and slicing syntax is so verbose you can't save any characters this way (e.g.a=(true false);[[ FIXEDSTRING = *$1* ]];echo ${a[$?]}
is six characters longer than my current approach; useful if I needed to convert exit status to true/false in multiple places, but not for a one-off use)- Stepped slicing of a string isn't a thing.