-
-
Save dualbus/6811562 to your computer and use it in GitHub Desktop.
| #!/bin/bash | |
| trap 'rm -rf "$tempdir"' EXIT | |
| tempdir=$(mktemp -d) | |
| cd "$tempdir" || exit 1 | |
| printf '%s\n' \ | |
| '(return 2>/dev/null); echo $?' \ | |
| > bash_return | |
| printf '%s\n' \ | |
| 'printf %s\\n "$((! BASH_LINENO))"' \ | |
| > bash_lineno | |
| printf '%s\n' 'should pass' | |
| for approach in bash_{lineno,return}; do | |
| printf '%s ' "$approach" | |
| { | |
| bash -c ". $approach" | |
| bash -s <<< ". $approach" | |
| printf '. %s\n' "$approach" > "$approach"_test; | |
| chmod +x "$approach"_test; | |
| ./"$approach"_test; | |
| bash "$approach"_test; | |
| . "$approach"_test; | |
| . "$approach"; | |
| } | tr '\n01' ' ox' | |
| printf ': %s\n' "$(< "$approach")" | |
| done | |
| printf '%.s-' {0..79}; printf \\n | |
| printf '%s\n' 'should fail' | |
| for approach in bash_{lineno,return}; do | |
| printf '%s ' "$approach" | |
| { | |
| bash "$approach" | |
| bash -s < "$approach" | |
| eval "$(<"$approach")" | |
| } | tr '\n01' ' ox' | |
| printf ': %s\n' "$(< "$approach")" | |
| done |
just an fyi, i had my own technique for this that i recently switched to (return 2>/dev/null) thanks to this.
adding this
printf '%s\n' \
'[[ ${BASH_SOURCE[0]} != $0 ]]; echo $?' \
> bash_sourcei got
should pass
bash_lineno x o o o o o : printf %s\\n "$((! BASH_LINENO))"
bash_return o o o o o o : (return 2>/dev/null); echo $?
bash_source o o o o o o : [[ ${BASH_SOURCE[0]} != $0 ]]; echo $?
--------------------------------------------------------------------------------
should fail
bash_lineno x x x : printf %s\\n "$((! BASH_LINENO))"
bash_return x x x : (return 2>/dev/null); echo $?
bash_source x o x : [[ ${BASH_SOURCE[0]} != $0 ]]; echo $?
it doesn't fail when it should... (return 2>/dev/null) seems to be the cleanest approach.
@bahamas10 Nice! I didn't see your reply in time. It's an ugly trick but it seems to work. If you find more situations where it could fail please tell me so :)
You need to write 'return 0' rather than just return, or else
false; source bash_return
prints 1.
And, when using trap 'rm -rf "$tempdir"' EXIT, always assume that the caller did export tempdir=/, and that you get a signal between the trap and the mktemp. (Actually, that's hard to arrange). So, either unset tempdir, or put the trap after the mktemp call.
@ejhuff Wow, this thing doesn't notify me. I agree with your points. Specially the second, I started doing: unset var; trap ' uses var ' FOO; var=... for this precisely, but I guess that was before I wrote this :-)
$ bash 2013-10-03-lhunath-bashlib
should pass
bash_lineno x o o o o o : printf %s\n "$((! BASH_LINENO))"
bash_return o o o o o o : (return 2>/dev/null); echo $?
should fail
bash_lineno x x x : printf %s\n "$((! BASH_LINENO))"
bash_return x x x : (return 2>/dev/null); echo $?