shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

Warn about "return" can only in a function or sourced script

Open rony36 opened this issue 11 years ago • 6 comments

"return" can only be used in a function or sourced script in Bash. It will causes an execution error. Here is a simple example.

#!/bin/bash
echo "Hello!"
return 18
echo "Hello you!"

In bash, it will show "Hello!" and "Hello you!" and return error code 0 with message line 3: local: can only be used in a function.

In zsh, it will show only "Hello!" and return error code 18.

May shellcheck check for this?

rony36 avatar Aug 04 '15 09:08 rony36

How would shellcheck know whether the script is being sourced or not?

aw-was-here avatar Aug 04 '15 10:08 aw-was-here

Shellcheck is never know ... Would this be a default off option?

rony36 avatar Aug 04 '15 11:08 rony36

I think it's safe to say this issue can be closed, due to what @aw-was-here pointed out. (CodeTriage brought me here... I'd like to help cut down on the number of open issues in this project.)

sayoder avatar Nov 29 '16 21:11 sayoder

Just leave it. There may be some option in the future.

koalaman avatar Dec 07 '16 18:12 koalaman

How would shellcheck know whether the script is being sourced or not?

Yes, make it optional if necessary.

Proposed heuristic :

  • the file has a shebang
  • the file defines one or more functions
  • the return statement is not inside any function context

alxdrl avatar Aug 14 '19 14:08 alxdrl

Duplicate of #281

stdedos avatar Jan 18 '20 01:01 stdedos