2011-08-28 9 views
19

Estoy tratando de entender el script "cdargs-bash.sh" con paquetes de cdargs. Y tengo una pregunta acerca de la función siguiente:reemplazar el carácter de nueva línea en la variable 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 

}

¿Cuál es el propósito de la prueba:

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

Aquí el lapso de pruebas sobre dos líneas; ¿Desea eliminar el carácter de nueva línea en $dir o tal vez por alguna otra razón? Estoy empezando a aprender scripts bash y he buscado en Google un tiempo pero no he podido encontrar ningún uso como este.

Respuesta

35

Sí, tiene razón, elimina el carácter de nueva línea. Creo que el propósito de la prueba es asegurarnos de que $dir no contenga líneas múltiples.

Como alternativa, puede quitar \newline por

${dir/$'\n'/} 

Esto no requiere dos líneas, así que creo que se ve mejor.

+0

bueno, la sugerencia que le da funciona muy bien. ¿La sustitución de la variable '$ '\ n'' aquí es? Simplemente no pude entenderlo. – yorua007

+4

No, se llama 'Citas ANSI-C', consulte http://www.gnu.org/software/bash/manual/bashref.html#ANSI_002dC-Cotting –

+0

oh, lo tengo. Muchas gracias. – yorua007

Cuestiones relacionadas