Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!