mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 11:19:45 +08:00
Created SC2152 (markdown)
31
SC2152.md
Normal file
31
SC2152.md
Normal file
@@ -0,0 +1,31 @@
|
||||
## Can only return 0-255. Other data should be written to stdout.
|
||||
|
||||
### Problematic code:
|
||||
|
||||
myfunc() {
|
||||
return "Hello $USER"
|
||||
}
|
||||
|
||||
### Correct code:
|
||||
|
||||
myfunc() {
|
||||
echo "Hello $USER"
|
||||
return 0
|
||||
}
|
||||
|
||||
### Rationale:
|
||||
|
||||
In many languages, `return` is used to return from the function with a final result.
|
||||
|
||||
In bash, `return` can only be used to signal success or failure (0 = success, 1-255 = failure), more akin to `throw/raise` in other languages.
|
||||
|
||||
Results should instead be written to stdout and captured:
|
||||
|
||||
message=$(myfunc)
|
||||
echo "The function wrote: $message"
|
||||
|
||||
In functions that return small integers, such as getting the cpu temperature, the value should still be written to stdout. `return` should be reserved for error conditions, such as "can't determine CPU temperature".
|
||||
|
||||
### Exceptions:
|
||||
|
||||
None
|
Reference in New Issue
Block a user