替换bash变量中的换行符?

yor*_*007 28 bash newline substitution

我试图用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 "^$1 " "$HOME/.cdargs"`
    if [ -z "$dir" ]; then
        bookmark="${1/\/*/}"
        if [ "$bookmark" != "$1" ]; then
            dir=`/bin/grep "^$bookmark " "$HOME/.cdargs"`
            extrapath=`echo "$1" | /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
Run Code Online (Sandbox Code Playgroud)

}

测试的目的是什么:

"$dir" != "${dir/
/}"
Run Code Online (Sandbox Code Playgroud)

这里测试跨越两条线; 是否要删除换行符$dir或者出于其他原因?我刚刚开始学习bash脚本,我用Google搜索了一段时间但找不到这样的用法.

Mu *_*iao 49

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

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

${dir/$'\n'/}
Run Code Online (Sandbox Code Playgroud)

这不需要两行,所以我觉得它看起来更好.

  • @ con-f-use` $ {dir // $'\n'/}`将替换所有出现的内容. (15认同)
  • 不,它被称为"ANSI-C Quoting",请参阅http://www.gnu.org/software/bash/manual/bashref.html#ANSI_002dC-Quoting (6认同)