bash 使用 cp 时脚本变量出现奇怪的结果

bash script variables weird results when using cp

如果我在 bash 脚本中使用 cp,复制的文件将在目标文件名周围有奇怪的字符。 目标名称来自操作的结果,它被放在一个变量中,并且回显该变量显示正常输出。

objective是用字符串命名文件

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

如果我启动脚本,回显看起来正常

    $ ./rename.sh
    mo-swc-56001

但是文件的命名方式不同

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

如您所见,该文件包含 echo 未显示的额外字符。

编辑:文件的换行符是这样的

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

我尝试了各种可能的方法来摆脱 ^M 字符,但这是数百次尝试的一个例子

    # 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

这条换行符将保留在那里。有什么想法吗?

编辑:疯了,唯一的方法是对输出执行 dos2unix...

看起来你的输出文件中有 \r 个字符,所以你可以在那里添加逻辑来删除它们,然后试试看。

#!/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"

唯一的方法是使用 dos2unix