Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Add warning about shorter if and && #127

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1909,6 +1909,36 @@ f()for i in "$@"; do echo "$i"; done
}
```

Important note: using the `&&` syntax in a function can lead to
unexpected results. For example:

```shell
func_example1() {
if [ $1 -gt 11 ]; then
return
fi
}

func_example2() {
[ $1 -gt 11 ] && return

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this use case one should explicitly supply exit code to return, so that it doesn't use last command's (test) exit status by default. And this is what the difference between the two constructions is. So that's kind of NOT unexpected result. See help return. I think this should be mentioned in this snippet to clarify what the "unexpected result" means, alongside the proper usage.

}

arg=10

func_example1 $arg
echo func_example1: $?

func_example2 $arg
echo func_example2: $?
```

results in

```shell
func_example1: 0
func_example2: 1
```

## Simpler `case` statement to set variable

The `:` built-in can be used to avoid repeating `variable=` in a case statement. The `$_` variable stores the last argument of the last command. `:` always succeeds so it can be used to store the variable value.
Expand Down