Home > database >  Bash function: Is there a way to check if a variable is local?
Bash function: Is there a way to check if a variable is local?

Time:03-27

Suppose that you have a function with a lot of options and that you save their value dynamically. After that, is there a way to check if a variable is local to a function?

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

    while getopts "$(printf '%s' {a..z} {A..Z})" option
    do
        case $option in
        [a-zA-Z]) local "$option"=1;;
               *) exit 1;;
        esac
    done

    # here's the problem:
    [[ ${a: 1} ]] && echo "option a is set"
    [[ ${b: 1} ]] && echo "option b is set"
    # etc...
}

Is there a way to check if a variable is 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