2011-08-28 113 views
19

我想了解與cdargs包「cdargs-bash.sh」腳本。我有一個關於在以下功能問題:在bash變量中替換換行符?

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 

}

什麼是測試目的:

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

這裏測試跨度兩行;它是否想要刪除$dir中的換行符或者可能是由於其他原因?我剛剛開始學習bash腳本,並且Google已經Google了一些時間,但找不到像這樣的用法。

回答

35

是的你是對的,它刪除換行符。我認爲測試的目的是確保$dir不包含多行。

或者,您也可以通過

${dir/$'\n'/} 

刪除\newline這並不需要兩條線,所以我認爲它看起來更好。

+0

好吧,您給出的建議效果很好。 '$'\ n''這裏是變量替換嗎?我只是無法理解它。 – yorua007

+4

不,它被稱爲'ANSI-C報價',請參閱http://www.gnu.org/software/bash/manual/bashref.html#ANSI_002dC-報價 –

+0

哦,我明白了。非常感謝。 – yorua007