mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2218 (markdown)
45
SC2218.md
Normal file
45
SC2218.md
Normal file
@@ -0,0 +1,45 @@
|
||||
## This function is only defined later. Move the definition up.
|
||||
|
||||
### Problematic code:
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
myfunction
|
||||
|
||||
myfunction() {
|
||||
echo "Hello World"
|
||||
}
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
myfunction() {
|
||||
echo "Hello World"
|
||||
}
|
||||
myfunction
|
||||
```
|
||||
|
||||
### Rationale:
|
||||
|
||||
You are calling a function that you are defining later in the file. The function definition must come first.
|
||||
|
||||
Function definitions are much like variable assignments, and define a name at the point the definition is "executed". This is why they must happen before their first use.
|
||||
|
||||
This is especially apparent when defining functions conditionally:
|
||||
|
||||
```
|
||||
case "$(uname -s)" in
|
||||
Linux) hi() { echo "Hello from Linux"; } ;;
|
||||
Darwin) hi() { echo "Hello from macOS"; } ;;
|
||||
*) hi() { echo "Hello from something else"; } ;;
|
||||
esac
|
||||
|
||||
hi
|
||||
```
|
||||
|
||||
|
||||
### Exceptions:
|
||||
|
||||
None.
|
Reference in New Issue
Block a user