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!
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"
From the discussion in the comments there are two problems:
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')
the literal $HOME in the variable $DIR can be substituted with envsubst like
DIR=$(echo $DIR | envsubst )
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")"