Actually, IFS and printf are not Bash-specific, they both work in POSIX compliant shells.
Unlike echo, which may collapse spaces and interpret special characters differently across systems, printf always prints exactly what you pass to it.
printf "%s\n" always preserves spaces/tabs → Works in sh, bash, dash, ksh, etc.
The default read behavior trims spaces, but setting IFS='' prevents this.
Code: Select all
var=' hello world '
IFS= read -r value <<EOF
$var
EOF
printf "%s\n" "$value" # Preserves spaces exactly
IFS works in all POSIX shells, including sh, dash, ksh, etc.
cat <<< is bash only.
eval "echo \${var}" Might collapse, and if var contains malicious code (e.g., var='$(rm -rf /)'), eval will execute it!
eval "echo \"\${var}\"" preserves spaces, but still risky.
printf "%s\n" "$var" preserves spaces and it's safe. Therefore it's the best universal solution.
MochiMoppel wrote: Wed Feb 26, 2025 2:58 am
superhik wrote: Tue Feb 25, 2025 9:41 pmAlso echo -E works in bash
This was already one of the proposed solutions - withouth the explicit -E option. As this is the default in echo anyway and therefore not required, do you see any scenario where the -E option makes a difference?
You're absolutely right! In modern Bash, echo -E is redundant because -E is the default behavior.
However, there are a few scenarios where echo -E can make a difference:
In POSIX sh, echo behavior varies by implementation. Some shells (like dash or BusyBox sh) might still interpret escape sequences by default, so using -E explicitly in Bash ensures consistency when running scripts across different shells.
In Bash, enabling shopt -s xpg_echo makes echo behave like echo -e, where \n and other escapes are interpreted by default.
Using echo -E here prevents this behavior.
If a user has an alias or function overriding echo in their shell profile (~/.bashrc, ~/.profile), echo might behave differently.
alias echo='echo -e'
Now, echo "Hello\nWorld" would always interpret \n as a newline, even in Bash.
Using echo -E forces literal output, ignoring the alias.