Comparing a string to the "newline" character

Bash shell questions
Post Reply
User avatar
MigrationUser
Posts: 336
Joined: 2021-Jul-12, 1:37 pm
Been thanked: 2 times
Contact:

Comparing a string to the "newline" character

Post by MigrationUser »

21 Jul 2010 14:55
bluesxman


I need to do a string comparison in a script I'm writing that will check to see if a variable contains only the newline character.

I'd like to do something like this, but it doesn't seem to recognise the "\n"

Code: Select all

if [ "${string}" = "\n" ] ; then .... ; fi
I have been able to kludge it using

Code: Select all

if ! echo "${string}" | grep "." ; then .... ; fi
but as grep is not a built-in command, adding it introduces a perceptible lag to the process, which is detrimental to the operation of the script.

Is it possible to do this with solely internal commands?

Last edited by bluesxman (21 Jul 2010 14:56)

cmd | *sh | ruby | chef

----------------------------

#2 20 Jul 2011 05:29
flabdablet


Couple of ways. In bash, you can do

Code: Select all

if [ "$string" = $'\n' ]
then
    echo String is a newline
fi
The $'' construction is a bashism, so if you want to do it more portably, simply define a variable that contains a newline and use that where you need one:

Code: Select all

newline='
'
if [ "$string" = "$newline" ] ...
That's a little more readable than the brute-force alternative

Code: Select all

if [ "$string" = '
' ] ...
original thread: oldforum/viewtopic.php?id=1056
Post Reply