Say I have a file myfile
in my current working directory. I want to set a variable if a command executes normally, but also use its result.
$ ls myfile && v=3
myfile
$ echo "$v"
3
But now I also want to pipe the result, so I use the { list; }
syntax to group the commands:
$ unset v $ { ls myfile && v=3; } | grep myf myfile $ echo "$v" # v is not set
Bash reference manual -> 3.2.4.3 Grouping Commands says:
{ list; }
Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.
So, to my understanding, v
should be set to 3. But it is not happening. Why?
It's not the curly braces that are causing a subshell to be created, it's the pipe.
To prove it:
To quote Greg: