I want to display a string in Bash like this
I'm a student
Of course you can do it like this
echo "I'm a student"
But how to accomplish this while using single quote around the string ?
echo 'I\'m a student'
does not work. But the following works:
echo $'I\'m a student'
From the man page of bash:
A single quote may not occur between single quotes, even when preceded by a backslash.
....
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.
echo $'I\'m a student!'
=> !': event not found
, this is not a real single quoted string which, in bash, should protect from any interpretation.
$ bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15) Copyright (C) 2007 Free Software Foundation, Inc.
Oct 31, 2016 at 13:06
The "ugly" solution mentioned by Glenn Jackman should actually be listed as a top level answer. It works well and is actually beautiful in some situations.
'I'"'"'m a student'
This ends the single quoted string after I
then immediately starts a double quoted string containing a single quote and then starts another single quoted string. Bash then concatenates all contiguous strings into one.
Beautiful!
$
does not necessarily have "+n" capacity. I'm not sure I'll have to test more. but it look to me like I'll be able to execute code that was already in single quotes stored into separate variables thanks to this.
The example below works because the escaped single quote \'
is technically between two single-quoted arguments
echo 'I'\''m a student'
Another way to workaround is to use printf
instead echo
and escape the required single quote with \x27:
printf 'I\x27m a student!\n'
I propose
echo "I'm a student"
like in other languages.
echo "I'm a student"
But how to accomplish this while using single quote around the string ?
Jan 23 at 19:51
3.1.2.2 Single Quotes
su -c '/etc/init.d/myservice start' -l myuser
(run by root)