I'm having trouble getting the length of a plain string in bash using # (is there a common name for this operator? The reference manual calls it a special parameter, but there are many of those). More specifically, I want to get the length of a path with : as a delimiter.
I've tried a few things, following the ${#parameter} syntax found in the manual, but they all return an error.
length=${#":/path/to/a/directory"} # "bad substitution"
length=${#':/path/to/a/directory'} # "bad substitution"
length=${#:/path/to/a/directory} # "syntax error: operand expected (error token is "/path/to/a/directory")"
# Removing the `:`
length=${#"/path/to/a/directory"} # "bad substitution"
length=${#'/path/to/a/directory'} # "bad substitution"
length=${#/path/to/a/directory} # `length` is set to 0
Clearly, using a variable works.
var=":/path/to/a/directory"
length=${#var} # `length` is correctly set to 21
It seems evident that bash does not support using # on a literal string, but could there be a workaround to using a variable?
No, there is no workaround. Any variable expansions, like
${#, work with variables, not strings.No, I do not think so. I call it "length operator" in my head. It would be really nice to have names for all those different expansions, they all are nameless.
The
$#variable is the special variable expanding to the number of arguments passed to a script. In the case of your shell,$#is 0, your shell was invoked with no parameters. The${#/path/to/a/directory}is parsed as${parameter/pattern/string}case, where the parts areparameter=#,pattern="path"andstring="to/a/directory".