r/ProgrammerTIL • u/cdrini • Dec 23 '21
Bash [bash] TIL dollar strings let you write escape chars
You think you know a language, and then it goes and pulls something like this!
For example:
$ echo $'a\nb'
a
b
#vs
$ echo 'a\nb'
a\nbCool little feature!
Here's a link: https://unix.stackexchange.com/a/48122/398190 ($"..." is even weirder...)
76
Upvotes
18
u/Resquid Dec 23 '21
For
echoyou could also use the-eflag: "enable interpretation of backslash escapes"But, the dollar sign is definitely very useful to keep in your pocket. I'm usually using it with
greportrlike:tr -d $'\t'1
u/zamlz-o_O Jan 19 '22
Is this POSIX?
1
u/funbike Jan 24 '22
Be careful. How this works depends on if you are using
/bin/shor/bin/bash.It's hard to test
/bin/shas various implementations handle escapes differently, because POSIX doesn't specify what to do with escape characters.bashis fairly consistent, howeverr.When using
/bin/sh, it's best to useprintfas its POSIX spec supports escaped characters.1
u/HamletOneLeg Feb 14 '22
I think double quotes does the same thing? Echo “a\nbc” gives me the same result on HPUX using ksh
Edit: actually single quotes does it too. Dunno if it’s my shell or HPUX lol
-1
u/arm1997 Dec 24 '21
Would try this in PHP