For your specific example, you can use a subshell, which effectively localizes all variables assigned within.
(
a='+::::::'
b="/etc/passwd"
grep -q "$a" "$b" || echo "$a" >> "$b"
)
سؤال
It seams wrong to repeat the same string twice
grep -q '+::::::' /etc/passwd || echo '+::::::' >> /etc/passwd
but if I do
{
local a='+::::::'
local b="/etc/passwd"
grep -q $a $b || echo $a >> $b
}
bash complains
-bash: local: can only be used in a function
Question
Is there a way to do local variables in Bash similar to how Perl does with the { ... }
?
المحلول
For your specific example, you can use a subshell, which effectively localizes all variables assigned within.
(
a='+::::::'
b="/etc/passwd"
grep -q "$a" "$b" || echo "$a" >> "$b"
)
نصائح أخرى
At least not with { ... }
.
The Advanced Bash-Scripting Guide states that
code blocks created with { ... }
create an anonymous function
, but all variables will still be visible to the remainder of the script.
This might be the wrong terminology as chepner stated.
The man page of bash, calling it group command
has the following to say:
{ list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recog‐ nized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter.
Here is some more info in local variables and their scope.