What is the value of ${#1}?

${#1} is the length (in number of characters) of $1 which is the first argument to the function.

So (( ${#1} == 0 )) is a convoluted way to test whether the first argument is empty (or unset, unset parameters appear as empty when expanded) or not.

To test for an empty parameter, the canonical way is:

[ -z "$1" ]

But there, more likely the intent was to check whether an argument was provided to the function in which case the syntax would be:

[ "$#" -eq 0 ]

(or (($# == 0)) if you want to make your script ksh/bash/zsh specific).

In both cases however, Bourne-like shells have short cuts for that:

test=${1:--} # set test to $1, or "-" if $1 is empty or not provided
test=${1--}  # set test to $1, or "-" if $1 is not provided

Now, if the intent is to pass that to cat or other text utility so that - (meaning stdin) is passed when no argument is provided, then you may not need any of that at all.

Instead of:

getlable() {
  test=${1--}
  cat -- "$test"
}

Just do:

getlable() {
  cat -- "$@"
}

The list of argument to the function will be passed as-is to cat. If there's no argument, cat will receive no argument (and then read from stdin as if it had been a single - argument). And if there's one or more arguments they will be all passed as-is to cat.


${#1} is the length of the first positional parameter.

In a running shell you can use

set -- foo bar
echo ${#1}
3

to set them.

Tags:

Shell