bash 替换bash变量中的换行符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7218781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:58:52  来源:igfitidea点击:

replace newline character in bash variable?

bashnewlinesubstitution

提问by yorua007

I am trying to understand the "cdargs-bash.sh" script with cdargs packages. And I have a question about in the following function:

我试图理解带有 cdargs 包的“cdargs-bash.sh”脚本。我对以下功能有疑问:

function _cdargs_get_dir ()
{
local bookmark extrapath
# if there is one exact match (possibly with extra path info after it),
# then just use that match without calling cdargs
if [ -e "$HOME/.cdargs" ]; then
    dir=`/bin/grep "^ " "$HOME/.cdargs"`
    if [ -z "$dir" ]; then
        bookmark="${1/\/*/}"
        if [ "$bookmark" != "" ]; then
            dir=`/bin/grep "^$bookmark " "$HOME/.cdargs"`
            extrapath=`echo "" | /bin/sed 's#^[^/]*/#/#'`
        fi
    fi
    [ -n "$dir" ] && dir=`echo "$dir" | /bin/sed 's/^[^ ]* //'`
fi
if [ -z "$dir" -o "$dir" != "${dir/
/}" ]; then
    # okay, we need cdargs to resolve this one.
    # note: intentionally retain any extra path to add back to selection.
    dir=
    if cdargs --noresolve "${1/\/*/}"; then
        dir=`cat "$HOME/.cdargsresult"`
        /bin/rm -f "$HOME/.cdargsresult";
    fi
fi
if [ -z "$dir" ]; then
    echo "Aborted: no directory selected" >&2
    return 1
fi
[ -n "$extrapath" ] && dir="$dir$extrapath"
if [ ! -d "$dir" ]; then
    echo "Failed: no such directory '$dir'" >&2
    return 2
fi

}

}

What's the purpose of the testing:

测试的目的是什么:

"$dir" != "${dir/
/}"

Here the testing span over two lines; does it want to remove the newline character in $diror maybe for some other reason? I am just starting to learn bash scripting and I have Googled some time but couldn't find any usage like this.

这里的测试跨越两行;它是要删除换行符$dir还是出于其他原因?我刚刚开始学习 bash 脚本,我在谷歌上搜索了一段时间,但找不到任何这样的用法。

回答by Mu Qiao

Yes you are right, it removes the newline character. I think the purpose of the test is to make sure $dirdoesn't contain multiple lines.

是的,你是对的,它删除了换行符。我认为测试的目的是确保$dir不包含多行。

Alternatively, you can remove \newlineby

或者,您可以\newline通过删除

${dir/$'\n'/}

This doesn't require two lines so I think it looks better.

这不需要两行,所以我认为它看起来更好。