Comando da shell $ {PWD / \ / $ upto \ / * // $ upto} não entendido

0

Eu vi uma função de shell para alterar dir até $ upto.

upto() {
    cd "${PWD/\/$upto\/*//$upto}"
}

Mas não entendo "${PWD/\/$upto\/*//$upto}" . Alguém poderia gentilmente explicar?

A função foi encontrada em uma resposta para um Unix & Pergunta do Linux Stack Exchange .

    
por Frozen Flame 13.12.2013 / 15:32

1 resposta

3

Resposta curta? Acontece que você pode fazer muitas manipulações com variáveis além de simplesmente inseri-las como você faria com $PWD . Citando o manual de referência do bash :

${parameter/pattern/string}

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with ‘#’, it must match at the beginning of the expanded value of parameter. If pattern begins with ‘%’, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is ‘@’ or ‘*’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

Portanto, neste exemplo: ${PWD/\/$upto\/*//$upto}

  • parâmetro é PWD .
  • padrão é /$upto/* (é para isso que as barras são invertidas, para evitar que as barras em padrão terminem o padrão prematuramente, e para evitar ligar o "substituir todas as correspondências" comportamento que você normalmente obteria de um padrão que começa com uma barra)
  • string é /$upto

Portanto, isso parece na variável $PWD (que o shell mantém como o diretório atual), encontra o primeiro ponto lá onde está o nome do diretório que está em $upto rodeado por barras (então essa configuração $upto to " dog " não encontrará um diretório chamado " dogfood ") e substituirá esse ponto e todo o resto do diretório atual por apenas " /$upto ".

    
por 13.12.2013 / 16:01

Tags