Echo -e escape sequences? - linux

After days of researching I still don't understand why :
echo -e a\nb
gives me an output of : anb
While
echo -e 'a\nb' -----> Gives me an output of
a
b
I understand that echo -e activates the escape sequence , So it should work on the first example but it doesn't .. I'm lost.
I tried same commands in Ubuntu and OpenSuse .. both , same results .
Any Help ?

In echo 'a\nb'
This means \n , \r, \r\n is the new line or enter key in your keyboard. It parses those string. so that the result is:
a
b
In echo a\nb, It doesnt parse but just print it as normal string.
To enable or disable backslash interpretation, you can -e to -E.
ref: https://en.wikipedia.org/wiki/Newline
ref: http://linux.die.net/man/1/echo

The shell interprets the \ character when the \ character is not quoted, and the shell (normally) interprets it differently than the echo command.
echo -e a\nb
In the above, the shell interprets \n as n, because the characters are not in quotes. So the shell passes the characters anb to the echo command.
echo -e 'a\nb'
In the above, the shell passes the exact characters a\nb to the echo command, because the single quotes tell the shell not to interpret the \.
Note that bash supports a form of quoting that interprets ANSI C escapes directly:
echo $'a\nb'

Related

Replacing text with mixed special characters in a file

I'm trying to replace a string VCC_TGL to $G_CORNER_SQL_DETAILS($corner+vcc_tgl)
I have tried using the perl one liner, but it is missing the $ character.
my $i="VCC_TGL";
my $test="\$G_CORNER_SQL_DETAILS(\$corner+vcc_tgl)";
print "replace $i with $test\n";
`perl -pi.back -e 's/$i/$test/' configure.tcl`;
The output im getting on executing the above perl script is ,
set vccio G_CORNER_SQL_DETAILS(corner+vcc_tgl)
You are passing a string containing special shell characters, e.g. $, through shell parsing, i.e. they are processed by the shell and therefore get lost:
$ perl -e '$test="XXX\$YYY"; qx/set -x; echo $test/'
+ echo XXX
Back-ticks, qx// and system("...") are prone to such problems and are unsafe in general.
You should instead use the safe array version of system(), i.e. bypass the shell completely so that parameters are passed into the called command as-is:
$ perl -e '$i="AAA"; $test="XXX\$YYY"; system(qw(echo perl -pi.back -e), "s/$i/$test/", qw(configure.tcl));'
perl -pi.back -e s/AAA/XXX$YYY/ configure.tcl

Bash: New line in echo string fails when output is piped to crontab [duplicate]

How do I print a newline? This merely prints \n:
$ echo -e "Hello,\nWorld!"
Hello,\nWorld!
Use printf instead:
printf "hello\nworld\n"
printf behaves more consistently across different environments than echo.
Make sure you are in Bash.
$ echo $0
bash
All these four ways work for me:
echo -e "Hello\nworld"
echo -e 'Hello\nworld'
echo Hello$'\n'world
echo Hello ; echo world
echo $'hello\nworld'
prints
hello
world
$'' strings use ANSI C Quoting:
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.
You could always do echo "".
For example,
echo "Hello,"
echo ""
echo "World!"
On the off chance that someone finds themselves beating their head against the wall trying to figure out why a coworker's script won't print newlines, look out for this:
#!/bin/bash
function GET_RECORDS()
{
echo -e "starting\n the process";
}
echo $(GET_RECORDS);
As in the above, the actual running of the method may itself be wrapped in an echo which supersedes any echos that may be in the method itself. Obviously, I watered this down for brevity. It was not so easy to spot!
You can then inform your comrades that a better way to execute functions would be like so:
#!/bin/bash
function GET_RECORDS()
{
echo -e "starting\n the process";
}
GET_RECORDS;
Simply type
echo
to get a new line
POSIX 7 on echo
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html
-e is not defined and backslashes are implementation defined:
If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined.
unless you have an optional XSI extension.
So I recommend that you should use printf instead, which is well specified:
format operand shall be used as the format string described in XBD File Format Notation [...]
the File Format Notation:
\n <newline> Move the printing position to the start of the next line.
Also keep in mind that Ubuntu 15.10 and most distros implement echo both as:
a Bash built-in: help echo
a standalone executable: which echo
which can lead to some confusion.
str='hello\nworld'
$ echo | sed "i$str"
hello
world
You can also do:
echo "hello
world"
This works both inside a script and from the command line.
On the command line, press Shift+Enter to do the line break inside the string.
This works for me on my macOS and my Ubuntu 18.04 (Bionic Beaver) system.
For only the question asked (not special characters etc) changing only double quotes to single quotes.
echo -e 'Hello,\nWorld!'
Results in:
Hello,
World!
There is a new parameter expansion added in Bash 4.4 that interprets escape sequences:
${parameter#operator} - E operator
The expansion is a string that is the value of parameter with
backslash escape sequences expanded as with the $'…' quoting
mechanism.
$ foo='hello\nworld'
$ echo "${foo#E}"
hello
world
I just use echo without any arguments:
echo "Hello"
echo
echo "World"
To print a new line with echo, use:
echo
or
echo -e '\n'
This could better be done as
x="\n"
echo -ne $x
-e option will interpret backslahes for the escape sequence
-n option will remove the trailing newline in the output
PS: the command echo has an effect of always including a trailing newline in the output so -n is required to turn that thing off (and make it less confusing)
My script:
echo "WARNINGS: $warningsFound WARNINGS FOUND:\n$warningStrings
Output:
WARNING : 2 WARNINGS FOUND:\nWarning, found the following local orphaned signature file:
On my Bash script I was getting mad as you until I've just tried:
echo "WARNING : $warningsFound WARNINGS FOUND:
$warningStrings"
Just hit Enter where you want to insert that jump. The output now is:
WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:
If you're writing scripts and will be echoing newlines as part of other messages several times, a nice cross-platform solution is to put a literal newline in a variable like so:
newline='
'
echo "first line${newline}second line"
echo "Error: example error message n${newline}${usage}" >&2 #requires usage to be defined
If the previous answers don't work, and there is a need to get a return value from their function:
function foo()
{
local v="Dimi";
local s="";
.....
s+="Some message here $v $1\n"
.....
echo $s
}
r=$(foo "my message");
echo -e $r;
Only this trick worked on a Linux system I was working on with this Bash version:
GNU bash, version 2.2.25(1)-release (x86_64-redhat-linux-gnu)
You could also use echo with braces,
$ (echo hello; echo world)
hello
world
This got me there....
outstuff=RESOURCE_GROUP=[$RESOURCE_GROUP]\\nAKS_CLUSTER_NAME=[$AKS_CLUSTER_NAME]\\nREGION_NAME=[$REGION_NAME]\\nVERSION=[$VERSION]\\nSUBNET-ID=[$SUBNET_ID]
printf $outstuff
Yields:
RESOURCE_GROUP=[akswork-rg]
AKS_CLUSTER_NAME=[aksworkshop-804]
REGION_NAME=[eastus]
VERSION=[1.16.7]
SUBNET-ID=[/subscriptions/{subidhere}/resourceGroups/makeakswork-rg/providers/Microsoft.Network/virtualNetworks/aks-vnet/subnets/aks-subnet]
Sometimes you can pass multiple strings separated by a space and it will be interpreted as \n.
For example when using a shell script for multi-line notifcations:
#!/bin/bash
notify-send 'notification success' 'another line' 'time now '`date +"%s"`
With jq:
$ jq -nr '"Hello,\nWorld"'
Hello,
World
Additional solution:
In cases, you have to echo a multiline of the long contents (such as code/ configurations)
For example:
A Bash script to generate codes/ configurations
echo -e,
printf might have some limitation
You can use some special char as a placeholder as a line break (such as ~) and replace it after the file was created using tr:
echo ${content} | tr '~' '\n' > $targetFile
It needs to invoke another program (tr) which should be fine, IMO.

Using a variable to replace lines in a file with backslashes

I want to add the string %%% to the beginning of some specific lines in a text file.
This is my script:
#!/bin/bash
a="c:\Temp"
sed "s/$a/%%%$a/g" <File.txt
And this is my File.txt content:
d:\Temp
c:\Temp
e:\Temp
But nothing changes when I execute it.
I think the 'sed' command is not finding the pattern, possibly due to the \ backslashes in the variable a.
I can find the c:\Temp line if I use grep with -F option (to not interpret strings):
cat File.txt | grep -F "$a"
But sed seems not to implement such '-F` option.
Not working neither:
sed 's/$a/%%%$a/g' <File.txt
sed 's/"$a"/%%%"$a"/g' <File.txt
I have found similar threads about replacing with sed, but they don't refer to variables.
How can I replace the desired lines by using a variable adding them the %%% char string?
EDIT: It would be fine that the $a variable could be entered via parameter when calling the script, so it will be assigned like:
a=$1
Try it like this:
#!/bin/sh
a='c:\\Temp' # single quotes
sed "s/$a/%%%$a/g" <File.txt # double quotes
Output:
Johns-MacBook-Pro:sed jcreasey$ sh x.sh
d:\Temp
e:\Temp
%%%c:\Temp
You need the double slash '\' to escape the '\'.
The single quotes won't expand the variables.
So you escape the slash in single quotes and pass it into the double quotes.
Of course you could also just do this:
#!/bin/sh
sed 's/\(.*Temp\)/%%%&/' <File.txt
If you want to get input from the command line you have to allow for the fact that \ is an escape character there too. So the user needs to type 'c:\\' or the interpreter will just wait for another character. Then once you get it, you will need to escape it again. (printf %q).
#!/bin/sh
b=`printf "%q" $1`
sed "s/\($b\)/%%% &/" < File.txt
The issue you are having has to do with substitution of your variable providing a regular expression looking for a literal c:Temp with the \ interpreted as an escape by the shell. There are a number of workarounds. Seeing the comments and having worked through the possibilities, the following will allow the unquoted entry of the search term:
#!/bin/bash
## validate that needed input is given on the command line
[ -n "$1" -a "$2" ] || {
printf "Error: insufficient input. Usage: %s <term> <file>\n" "${0//*\//}" >&2
exit 1
}
## validate that the filename given is readable
[ -r "$2" ] || {
printf "Error: file not readable '%s'\n" "$2" >&2
exit 1
}
a="$1" # assign a
filenm="$2" # assign filename
## test and fix the search term entered
[[ "$a" =~ '/' ]] || a="${a/:/:\\}" # test if \ removed by shell, if so replace
a="${a/\\/\\\\}" # add second \
sed -e "s/$a/%%%$a/g" "$filenm" # call sed with output to stdout
Usage:
$ bash sedwinpath.sh c:\Temp dat/winpath.txt
d:\Temp
%%%c:\Temp
e:\Temp
Note: This allows both single-quoted or unquoted entry of the dos path search term. To edit in place use sed -i. Additionally, the [[ operator and =~ operator are limited to bash.
I could have sworn the original question said replace, but to append, just as you suggest in the comments. I have updated the code with:
sed -e "s/$a/%%%$a/g" "$filenm"
Which provides the new output:
$ bash sedwinpath.sh c:\Temp dat/winpath.txt
d:\Temp
%%%c:\Temp
e:\Temp
Remember: If you want to edit the file in place use sed -i or sed -i.bak which will edit the actual file (and if -i.bak is given create a backup of the original in originalname.bak). Let me know if that is not what you intended and I'm happy to edit again.
Creating your script with a positional parameter of $1
#!/bin/bash
a="$1"
cat <file path>|sed "s/"$1"/%%%"$1"/g" > "temporary file"
Now whenever you want sed to find "c:\Temp" you need to use your script command line as follows
bash <my executing script> c:\\\\Temp
The first backslash will make bash interpret any backslashes that follows therefore what will be save in variable "a" in your executing script is "c:\\Temp". Now substituting this variable in sed will cause sed to interpret 1 backlash since the first backslash in this variable will cause sed to start interpreting the other backlash.
when you Open your temporary file you will see:
d:\Temp
%%%c:\Temp
e:\Temp

Escape special characters in echo

http://www.grymoire.com/Unix/Quote.html shows a list of special characters. Is there a parameter/option for echo where I can treat everything that comes after the echo as a string?
In python, i could use the """...""" or '''...'''.
$ python
>>> text = '''#"`\|^!###%$#$^%$&%^*()?/\;:$#$#$?$$$!&&'''
>>> print text
#"`\|^!###%$#$^%$&%^*()?/\;:$#$#$?$$$!&&
I can do the same in unix's echo with ''' but not """, why is that so?
$ echo #"`\|^!###%$#$^%$&%^*()?/\;:$#$#$?$$$!&&
$ echo '''#"`\|^!###%$#$^%$&%^*()?/\;:$#$#$?$$$!&&'''
#"`\|^!###%$#$^%$&%^*()?/\;:$#$#$?$$$!&&
$ echo """'''#"`\|^!###%$#$^%$&%^*()?/\;:$#$#$?$$$!&&"""
bash: !###%$#$^%$: event not found
What happens if i have a string like this?
#"`\|^!###%$#$^%'''$&%^*()?/\;:$#$"""#$?$$$!&&
How should I echo such a string? (the following command doesn't work)
echo '''#"`\|^!###%$#$^%'''$&%^*()?/\;:$#$"""#$?$$$!&&'''
Use printf:
$ printf "%s\n" $'#"`\|^!###%$#$^%$&%^*()?/\;:$#$#$?$$$!&&'
#"`\|^!###%$#$^%$&%^*()?/\;:$#$#$?$$$!&&
$ printf "%s\n" $'#"`\|^!###%$#$^%\'\'\'$&%^*()?/\;:$#$"""#$?$$$!&&'
#"`\|^!###%$#$^%'''$&%^*()?/\;:$#$"""#$?$$$!&&
You might note that single quotes ' need to be escaped.
In order to assign the output to a variable:
$ foo=$(printf "%s\n" $'#"`\|^!###%$#$^%\'\'\'$&%^*()?/\;:$#$"""#$?$$$!&&')
$ echo $foo
#"`\|^!###%$#$^%'''$&%^*()?/\;:$#$"""#$?$$$!&&
It is because shell applies all expansion rules inside a string double quotes ". $ or ! are special Unix characters to denote variable or event hence you get that error.
I think it is because of your shell (bash), which expands/interprets double quotes.
This does not apply for single quotes.
For details, please have a look at Bash - Shell Expansion.
For the echo command there is the -e option which enables interpretation of backslash escapes - which might help.

What is the purpose of the -e flag in this script?

I got a script from - http://www.thegeekstuff.com/2010/06/bash-conditional-expression/
It is -
$ cat exist.sh
#! /bin/bash
file=$1
if [ -e $file ]
then
echo -e "File $file exists"
else
echo -e "File $file doesnt exists"
fi
$ ./exist.sh /usr/bin/boot.ini
File /usr/bin/boot.ini exists
I used the same code without -e near both the echo and it works. So, what is the purpose of using -e there ?
The -e flag enables interpretation of the following backslash-escaped
characters in each STRING:
\a alert (bell)
\b backspace
\c suppress trailing newline
\e escape
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\NNN
the character whose ASCII code is NNN (octal); if NNN is not
a valid octal number, it is printed literally.
\xnnn
the character whose ASCII code is the hexadecimal value
nnn (one to three digits)
Source: http://ss64.com/bash/echo.html
-e enables interpretation of backslash escapes, but answering your question, about the purpose of it being there, it seems to be none at all. It can even be harmful. echo -e is useful if you want to include those backslashed characters in the string, but that is not the case in your example, unless $file has them, and then this can happen:
$ touch test\\test
$ ls
exist.sh test\test
$ ./exist.sh test\\test
File test est exists
Without the -e you get the correct file name. Of course, this is all academic because it's unlikely that files will contain backslashed entities, but then we can conclude those switches were put there with the express goal of confusing you.

Resources