首页 > 解决方案 > 连接从 bash 中的函数返回的字符串

问题描述

我正在尝试从包含特定版本的主要、次要和补丁元素的文本文件中提取版本字符串。

该文件被命名versioninfo.txt,其内容如下:

MAJOR 2
MINOR 0
PATCH 0

我正在编写一个 bash 脚本来从该文件中提取值并生成一个类似的字符串,v2.0.0但是在构建完整的版本字符串时我很挣扎。

这是我写的 bash 脚本

#!/bin/bash

function extractVersionElement() {
    line=$(sed "${1}q;d" versioninfo.txt)
    version="${line#* }"
    echo "${version}"
}

function extractVersion() {
    major="$(extractVersionElement 1)"
    minor="$(extractVersionElement 2)"
    patch="$(extractVersionElement 3)"

    echo "major: ${major}"
    echo "minor: ${minor}"
    echo "patch: ${patch}"
}

version="$(extractVersion)"
echo "$version"

哪个输出,正确读取单个版本元素:

$ ./extract_version.sh
major: 2
minor: 0
patch: 0

将脚本更改为:

#!/bin/bash

function extractVersionElement() {
    line=$(sed "${1}q;d" versioninfo.txt)
    version="${line#* }"
    echo "${version}"
}

function extractVersion() {
    major="$(extractVersionElement 1)"
    minor="$(extractVersionElement 2)"
    patch="$(extractVersionElement 3)"

    # Here I try to create the complete version string
    echo "v${major}.${minor}.${patch}"
}

version="$(extractVersion)"
echo "$version"

输出以下内容,截断输出:

$ ./extract_version.sh
.0

关于如何解决这个问题的任何想法?


工作脚本

问题是由\r每一行的末尾引起的。这是解决问题的工作脚本:

#!/bin/bash

function extractVersionElement() {
    # read the nth line of the versioninfo file
    line=$(sed "${1}q;d" versioninfo.txt)

    # remove \r and \n from the string which were causing
    # problems when creating the final version string
    line=${line//[$'\t\r\n']}

    # extract the version after the space
    version="${line#* }"

    # return the read version
    echo "${version}"
}

function extractVersion() {
    major="$(extractVersionElement 1)"
    minor="$(extractVersionElement 2)"
    patch="$(extractVersionElement 3)"

    # combine the three version elements into one version string
    echo "v${major}.${minor}.${patch}"
}

version="$(extractVersion)"
echo "$version"

标签: stringbash

解决方案


推荐阅读