Justin clarified his question in his first comment on quanta's answer. He is reading in a line of text using read
(or by some other dynamic means) and wants to expand the tilde.
The question becomes "How do you perform tilde expansion on the contents of a variable?"
The general approach is to use eval
, but it comes with some important caveats, namely spaces and output redirection (>
) in the variable. The following seems to work for me:
read -p "Provide the destination directory: " DESTINATION
if [ ! -d "`eval echo ${DESTINATION//>}`" ]; then
echo "'$DESTINATION' does not exist." >&2;
exit 1;
fi
Try it with each of the following inputs:
~
~/existing_dir
~/existing dir with spaces
~/nonexistant_dir
~/nonexistant dir with spaces
~/string containing > redirection
~/string containing > redirection > again and >> again
Explanation
- The
${mypath//>}
strips out >
characters which could clobber a file during the eval
.
- The
eval echo ...
is what does the actual tilde expansion
- The double-quotes around the
eval
are for support of filenames with spaces.
As a supplement to this, you can improve the UX by adding the -e
option to read:
read -p "Provide the destination directory: " -e DESTINATION
Now when the user types in tilde and hits tab, it will expand. This approach does not replace the eval approach above, however, as the expansion only happens if the user hits tab. If he just types in ~/foo and hits enter, it will remain as a tilde.
See also:
cd "~/Desktop"
you also get an error. It has to be unquoted or stored as a variable (without quotes). For example,a=~/Desktop; cd $a;
works but nota="~/Desktop"; cd Desktop;
See serverfault.com/questions/417252/…