Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

258
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda