BashScripts.org
http://bashscripts.org/forum/

TILDE EXPANSION WANTED
http://bashscripts.org/forum/viewtopic.php?f=16&t=906
Page 1 of 1

Author:  timsoft [ Wed Oct 07, 2009 5:03 am ]
Post subject:  TILDE EXPANSION WANTED

I have a script as follows which as part of its function tries the following

MYFILE="~/myprogram/datafile"
if ! [ -e "$MYFILE" ]; then
echo file $MYFILE not there
fi
unfortunately, the ~ is not expanded to /home/username
and so the file is never found.
the MYFILE variable value may have spaces in it. eg "~/my nasty path/yuck data"

Any clues on a generic way to expand the path in the variable would be appreciated. thanks
Tim

Author:  Watael [ Wed Oct 07, 2009 5:47 am ]
Post subject:  Re: TILDE EXPANSION WANTED

Code:
myFile=~/"myprogram/datafile"
if ! [ -e "$myFile" ]
then
   echo "file $myFile not there"
else
   echo "$(basename "$myFile") is at $(dirname "$myFile")"
fi

Author:  timsoft [ Wed Oct 07, 2009 7:23 am ]
Post subject:  Re: TILDE EXPANSION WANTED

thanks for such a quick response watael,

and to make that slightly more generic
Code:
myfile="~/myprogram/datafile"
if [ `echo $myfile|cut -b-2` = "~/" ]; then
  myfile=~/`echo $myfile|cut -b3-`
fi

should work when initial value of myfile is not known

eg:
Code:
read myfile
if [ `echo $myfile|cut -b-2` = "~/" ]; then
  myfile=~/`echo $myfile|cut -b3-`
fi
echo myfile is $myfile

Author:  Watael [ Wed Oct 07, 2009 10:10 am ]
Post subject:  Re: TILDE EXPANSION WANTED

Code:
cut -b-2 <<<"$myfile"
looks nicer to me, and uses one command less

Page 1 of 1 All times are UTC - 6 hours
© 2000, 2002, 2005, 2007 phpBB Group • http://www.phpbb.com