Skip to content

Instantly share code, notes, and snippets.

@notwa
Last active February 24, 2024 09:22
Show Gist options
  • Save notwa/5b8dda28e571b27638fb33e08dc1ba21 to your computer and use it in GitHub Desktop.
Save notwa/5b8dda28e571b27638fb33e08dc1ba21 to your computer and use it in GitHub Desktop.
set -e is kinda useless
#!/usr/bin/env sh
# run this shell script with one of these shells:
# zsh, bash, dash, or (busybox) ash.
set -e
# false # this exits the shell immediately.
# false || false # this exits as well.
false && true # wait, what?
! true # huh?
fun() {
false # this *should* cause, the shell to exit, right...?
[ "$1" = 0 ]
}
if fun 0; then echo wat 1; fi
if false; then echo nope; elif fun 0; then echo wat 2; fi
i=0
while fun $i; do i=1; done
until fun $i; do i=0; done
# ! fun 0 # this exits zsh, and only zsh.
# (! (! fun 0)) # this exits bash, and only bash.
fun 0 && echo wat 3 || echo nope
fun 1 && echo nope
fun 0 || echo nope
echo aborting...
fun 0 # let's get out of here.
echo at least that works.
@notwa
Copy link
Author

notwa commented Feb 23, 2024

(set -e; (! { false; true; }))
if [ $? = 0 ]; then
    echo "You are running bash!"
fi

@notwa
Copy link
Author

notwa commented Feb 23, 2024

(set -e; ! $( false; true ))
if [ $? = 0 ]; then
    echo "You are running dash or mksh or posh!"
fi

@notwa
Copy link
Author

notwa commented Feb 23, 2024

(set -e;f(){ :;};! f;:)
if [ $? != 0 ]; then
    echo "You are running zsh!"
fi

@notwa
Copy link
Author

notwa commented Feb 24, 2024

found this one in the posh bug list:

if while :;do ! break;done; then
    echo "You are running mksh or posh or ysh!"
fi

in this case, ysh is oil shell 0.20.0 invoked as such: osh -o ysh:all +o strict_errexit +o simple_test_builtin

@notwa
Copy link
Author

notwa commented Feb 24, 2024

if ! (! return 0)2>&-; then
    echo "You are running dash or busybox ash or yash!"
fi

@notwa
Copy link
Author

notwa commented Feb 24, 2024

(set -e;$([ ];:))
if [ $? = 0 ]; then
    echo "You are running bash or busybox ash!"
fi

@notwa
Copy link
Author

notwa commented Feb 24, 2024

parser exploitation with squelched error message:

#!/usr/bin/env sh
set -e # you can remove this
echo This text is seen in any shell.
! { return 0;} 2>&- # exit any shell that isn't bash
echo This text is only seen in bash.

some shells (dash, busybox ash, yash) will exit the script with a nonzero value (1) so watch out for that

@notwa
Copy link
Author

notwa commented Feb 24, 2024

if (f(){ ! return;};f); then
    echo "You are running bash or mksh or ksh or posh!"
fi

subshell optional but then you're clobbering f()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment