Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

256
Visualizações
Expand environmental variable from grep output in bash script

I'm new to bash scripting, and I'm just trying to get this working. What I'm trying to get is a script that cd's to the default download directory, e.g. /home/davide/Downloads, and downloads a file from there in Ubuntu. I'm getting the default download directory like:

OUTPUT=$(grep DOWNLOAD $HOME/.config/user-dirs.dirs)
DIR=$(echo $OUTPUT | cut -f 2 -d "=" | tr "\"" "\n")

which is working fine. DIR is a string like:

$HOME/Downloads

The problem arises when I try to cd to it. It does something like:

cd $HOME/Downloads

which throws an error, while instead it should:

cd /home/davide/Downloads

I've searched quite a lot and it appears to me that the expansion should be completed. I've got it to expand by using the eval command, but it appears like it should be the very last resort.

Thank you for your help!

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Using gnu provided envsubst that substitutes environment variables in shell format strings:

dir=$(awk -F '["=]+' '/DOWNLOAD/{print $2}' file | envsubst)
echo "$dir"
# will output /home/user/Downloads
cd "$dir"
over 4 years ago · Santiago Trujillo Relatório

0

From the discussion in the comments there are two problems:

  1. there is a newline in the $DIR. I believe this is the cause of your original error. I would suggest to use a different way to determine $DIR:

    DIR=$(echo $OUTPUT | sed -r 's/.*="(.*)"/\1/g')
    
  2. the literal $HOME in the variable $DIR can be substituted with envsubst like

    DIR=$(echo $DIR | envsubst )
    
over 4 years ago · Santiago Trujillo Relatório

0

Try this:

cd "$(grep DOWNLOAD $HOME/.config/user-dirs.dirs | cut -f 2 -d "=" | tr "\"" "\n")"

Or, if that doesn't work:

cd "$(grep DOWNLOAD $HOME/.config/user-dirs.dirs | cut -f 2 -d "=" | tr "\"" "\n" | tr -d "\n")"
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda