Search code examples
scriptingcarriage-returncp

bash script variables weird results when using cp


If I use cp inside a bash script the copied file will have weird charachters around the destination filename. The destination name comes from the results of an operation, it's put inside a variable, and echoing the variable shows normal output.

The objective is to name a file after a string.

    #!/bin/bash
    newname=`cat outputfile | grep 'hostname ' | sed 's/hostname //g'
    newecho=`echo $newname`
    echo $newecho
    cp outputfile "$newecho"

If I launch the script the echo looks ok

    $ ./rename.sh
    mo-swc-56001

However the file is named differently

    ~$ ls
    'mo-swc-56001'$'\r'

As you can see the file contains extra charachters which the echo does not show.

Edit: the newline of the file is like this

    # file outputfile
    outputfile: ASCII text, with CRLF, CR line terminators

I tried in every possible way to get rid of the ^M charachter but this is an example of the hundreds of attempts

    # cat outputfile | grep 'hostname ' | sed 's/hostname //g' | cat -v
    mo-swc-56001^M

    # cat outputfile | grep 'hostname ' | sed 's/hostname //g' | cat -v |  sed 's/\r//g' | cat -v
    mo-swc-56001^M

This newline will stay there. Any ideas?

Edit: crazy, the only way is to perform a dos2unix on the output...


Solution

  • Looks like your outputfile has \r characters in it, so you could add logic there to remove them and give it a try then.

    #!/bin/bash
    ##remove control M first from outputfile  by tr command.
    tr -d '\r' < outputfile  > temp && mv temp outputfile
    newname=$(sed 's/hostname //g' outputfile)
    newecho=`echo $newname`
    echo $newecho
    cp outputfile "$newecho"