string - 连接从 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"
解决方案
推荐阅读
- visual-studio - 删除 Visual Studio 中所有禁用的断点
- javascript - 过渡导致文本和按钮隐藏在图像后面
- python - 如何在立交桥查询中连接字符串
- python - 在countour plot python中比较两个不同的数据集
- firebase-authentication - firebase / google authentication自定义密码重置链接不能在url中使用#
- elasticsearch - 最小聚合的弹性过滤器
- python - Python - 将 Google 表格行转换为字符串
- android - java.lang.NoClassDefFoundError: 解析失败:Lcom/huawei/hms/ads/identifier/AdvertisingIdClient;
- symfony - Symfony 5.2 错误:目录“var/cache/dev/jms_serializer”不存在
- sql-server - 约束逻辑和作业