Home > Net >  Bash function: Is there a way to check if a variable was defined locally?
Bash function: Is there a way to check if a variable was defined locally?

Time:03-27

Suppose that you have a function with a lot of options and that you decide to store their value dynamically:

#!/bin/bash
fun() {
    local __option

    while getopts ":$(printf '%s:' {a..z} {A..Z})" __option
    do
        case $__option in
        [[:alpha:])
            # ... 
            local "__$__option"="$OPTARG"
        esac
    done

    # here you might get a conflict with external variables:
    [[ ${__a: 1} ]] && echo "option a is set"
    [[ ${__b: 1} ]] && echo "option b is set"
    # etc...
    [[ ${__Z: 1} ]] && echo "option Z is set"
}

Is there a way to check if a variable was defined locally?

CodePudding user response:

You can definitely detect a variable is local (if it has been declared with one of Bash's declare, local, typeset statements).

Here is an illustration:

#!/usr/bin/env bash

a=3
b=2

fn() {
  declare a=1
  b=7
  if local -p a >/dev/null 2>&1; then
    printf 'a is local with value %s\n' "$a"
  else
    printf 'a is not local with value %s\n' "$a"
  fi
  if local -p b >/dev/null 2>&1; then
    printf 'b is local with value %s\n' "$b"
  else
    printf 'b is not local with value %s\n' "$b"
  fi
}


fn

Output is:

a is local with value 1
b is not local with value 7
  •  Tags:  
  • bash
  • Related