Created
July 28, 2025 00:20
-
-
Save josharian/41c71c1321a37eb58e2de9ab4c2dda58 to your computer and use it in GitHub Desktop.
test null behavior in shells
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 | |
# Test script to understand null byte behavior across different shell constructs | |
# Run this with different shells: bash, zsh, dash, etc. | |
echo "=== Shell: $0 ===" | |
echo "Shell version info:" | |
if command -v bash >/dev/null 2>&1; then | |
bash --version | head -1 | |
fi | |
echo | |
# Helper function to show output with visible null bytes | |
show_output() { | |
local desc="$1" | |
shift | |
echo "--- $desc ---" | |
echo "Command: $*" | |
echo -n "Output (od -c): " | |
"$@" | od -c | head -1 | |
echo -n "Byte count: " | |
"$@" | wc -c | |
echo | |
} | |
echo "=== printf tests ===" | |
show_output "printf with \\x00" printf "before\\x00after" | |
show_output "printf with \\000" printf "before\\000after" | |
show_output "printf with literal null" printf "before\x00after" | |
echo "=== echo tests ===" | |
show_output "echo with \\x00" echo "before\\x00after" | |
show_output "echo -e with \\x00" echo -e "before\\x00after" | |
show_output "echo with \$'\\x00'" echo $'before\x00after' | |
show_output "echo with \$'\\\\x00'" echo $'before\\x00after' | |
echo "=== variable expansion tests ===" | |
show_output "variable with literal null" sh -c 'a="before\x00after"; echo "$a"' | |
show_output "variable with \$'\\x00'" sh -c 'a=$'"'"'before\x00after'"'"'; echo "$a"' | |
show_output "variable with \$'\\\\x00'" sh -c 'a=$'"'"'before\\x00after'"'"'; echo "$a"' | |
echo "=== command substitution tests ===" | |
show_output "command subst with printf" sh -c 'echo "$(printf "before\\x00after")"' | |
show_output "command subst with echo \$''" sh -c 'echo "$(echo $'"'"'before\x00after'"'"')"' | |
echo "=== assignment and quoting ===" | |
show_output "assignment then printf %s" sh -c 'a=$'"'"'before\x00after'"'"'; printf "%s" "$a"' | |
show_output "assignment then echo" sh -c 'a=$'"'"'before\x00after'"'"'; echo "$a"' | |
echo "=== test with other escape sequences ===" | |
show_output "printf with \\n and \\x00" printf "line1\\nline2\\x00line3\\nline4" | |
show_output "printf with \\t and \\x00" printf "col1\\tcol2\\x00col3\\tcol4" | |
echo "=== edge cases ===" | |
show_output "printf empty \\x00" printf "\\x00" | |
show_output "printf only \\x00" printf "\\x00after" | |
show_output "printf \\x00 at end" printf "before\\x00" | |
show_output "multiple \\x00" printf "a\\x00b\\x00c" | |
echo "Done!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment