Created
October 3, 2013 15:18
-
-
Save dualbus/6811562 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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 :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 :)