Question

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 { ... }?

Was it helpful?

Solution

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"
)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top