Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Please explain the usage of ${#1} below:

getlable ()     
{
    if (( ${#1} == 0 )); then test="-"; else test="${1}"; fi;
}
share|improve this question
1  
Just wondering: did you bother putting an echo ${#1} before that statement to see what the value is? If so, you should generally include what you found in that research in the question, and perhaps an explanation of why it didn't help. – jpmc26 Jan 28 at 7:29
up vote 24 down vote accepted

${#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.

share|improve this answer
    
now that's how you provide an excellent answer :) – Yerken Jan 28 at 6:53

${#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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.