RJ Cole
RJ Cole

Reputation: 2680

Using tr to trim newlines from command-line argument ignored

I have a shell script that needs to trim newline from input. I am trying to trim new line like so:

    param=$1
    trimmed_param=$(echo $param | tr -d "\n")

    # is the new line in my trimmed_param?  yes
    echo $trimmed_param| od -xc

    # if i just run the tr -d on the data, it's trimmed. 
    # why is it not trimmed in the dynamic execution of echo in line 2
    echo $param| tr -d "\n" |od -xc

I run it from command line as follows:

    sh test.sh someword

And I get this output:

    0000000    6f73    656d    6f77    6472    000a
              s   o   m   e   w   o   r   d  \n
    0000011
    0000000    6f73    656d    6f77    6472
              s   o   m   e   w   o   r   d
    0000010 

The last command in the script echos what I would think trimmed_param would be if the tr -d "\n" had worked in line 2. What am I missing?

I realize I can use sed etc but ... I would love to understand why this method is failing.

Upvotes: 0

Views: 581

Answers (1)

hek2mgl
hek2mgl

Reputation: 157927

There has never been a newline in the param. It's the echo which appends the newline. Try

# script.sh
param=$1
printf "%s" "${param}" | od -xc

Then

bash script.sh foo

gives you

0000000    6f66    006f
          f   o   o
0000003

Upvotes: 3

Related Questions