Skip to content

Instantly share code, notes, and snippets.

@dualbus
Created October 3, 2013 15:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dualbus/6811562 to your computer and use it in GitHub Desktop.
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
@dualbus
Copy link
Author

dualbus commented Dec 20, 2013

@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 :)

@ejhuff
Copy link

ejhuff commented Oct 7, 2014

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.

@dualbus
Copy link
Author

dualbus commented Apr 1, 2015

@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