Skip to content

Instantly share code, notes, and snippets.

@dgoade
Created May 2, 2015 13:01
Show Gist options
  • Save dgoade/369d1653596f05058a27 to your computer and use it in GitHub Desktop.
Save dgoade/369d1653596f05058a27 to your computer and use it in GitHub Desktop.
Bash Cookbook: Use declare to scope variables in Bash
#!/bin/bash
# The declare builtin allows you to limit the scope of variables in bash
BAZ="OTHER"
foo ()
{
declare BAZ="THIS"
echo "Inside foo(), BAZ=${BAZ}"
}
bar ()
{
declare BAZ="THAT"
echo "Inside bar(), BAZ=${BAZ}"
}
echo "Outside of foo() and bar(), BAZ=${BAZ}"
foo
echo "Between calls to foo() and bar(), still BAZ=${BAZ}"
bar
echo "Outside of foo() and bar(), still BAZ=${BAZ}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment