Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand environmental variable from grep output in bash script

Tags:

linux

bash

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!

like image 338
Pax_1601 Avatar asked Dec 07 '25 07:12

Pax_1601


1 Answers

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"
like image 127
anubhava Avatar answered Dec 09 '25 23:12

anubhava