Question for you all.
I was working on a bash script and working out some logic for command chaining and grouping for executing different functions in my script based on the return status of other functions.
I know you can group commands with ()
, which spawns a subshell, and within the grouping you can chain with ;
, &&
, and ||
.
I also know that you can group commands with {}
, but, within the curly braces you can only separate commands with ;
.
EDIT: the above statement of the curly braces only allowing ;
is incorrect. I misunderstood what I had read. @SheeEttin@lemmy.zip pointed out my mistake.
The requirement is that the list of commands in the curly braces needs to be terminated with a semicolon or a newline character, and in the script, I unknowingly was meeting the rules by using the newlines to make the code easier to read for myself.
END EDIT:
In the script, for readability I did group the commands across lines kind of like a function.
The script is pretty simple. I created a few functions with echo commands to test the logic. the script asks for input of foo or bar. The first function has an if
, and if the input is foo, it executes. If it’s bar it returns 1.
The return of 1 triggers the or (||
) and executes the second command group.
The idea was, if the user inputs foo
, the first group triggers printing foo baz
to stdout. If the user inputs bar
, the foo
function returns 1, the baz function does not execute, the or is triggered, and bar but
is printed to stdout
Here’s the script (which executes as described):
Can anyone explain why I’m able to group with curly braces and still use &&
inside them?
(Also, the reason I want to use the curly braces is I don’t want to spawn a subshell. I want variable persistence in the current shell)
#! /usr/bin/bash
# BEGIN FUNCTIONS #
foo () {
if [[ "${input}" = foo ]]; then
echo "foo"
return 0
else
return 1
fi
}
bar () {
echo "bar"
}
baz () {
echo "baz"
}
but () {
echo "but"
}
# END FUNCTIONS #
read -p "foo or bar? " input
{
foo &&
baz
} ||
{
bar &&
but
}
Ah! I misinterpreted what I read! I found that exact same reference link when looking into this and I misinterpreted this:
to mean that it required the semicolon as the command separator. That explains why my script works. The newline closes each group, and the other operators are allowed, the list just needs to be closed. Thank you!