Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

A bash function to expand tildes in a filename? (and also works in zsh and ksh 93u+)

45 views
Skip to first unread message

Rocky Bernstein

unread,
Apr 3, 2013, 7:01:16 PM4/3/13
to
I would like to write a shell function that takes a string and sets variable $filename a string that expands filename tildes in the string (e.g. ~ or ~rocky) the same as bash would do. If the string has embedded blanks, those blanks should be preserved in the string. Unix, OSX, Windows all allow blanks in filenames and directories.

Below is some code that worked in bash 4.2 until February 2012. Also given is code that works in ksh and zsh. Can anyone come up with something that works in all 3?

(I use this code in the bash debugger http://bashdb.sf.net)

Thanks.


glob_filename_bash_old() {
printf -v filename "%q" "$1"
typeset cmd="filename=$filename"
eval $cmd
[[ -r $filename ]]
}

# $1 contains the name you want to glob. return 0 if exists and is
# readable or 1 if not.
# The result will be in variable $filename which is assumed to be
# local'd by the caller
glob_filename_ksh_zsh() {
typeset cmd="filename=$(expr $1)"
eval "$cmd"
[[ -r "$filename" ]]
}

if glob_filename_bash_old '~' ; then
echo "bash version < 4.3 for ~ way works"
else
echo "bash version < 4.3 for ~ does not work"
fi

if glob_filename_ksh_zsh '~' ; then
echo "zsh/ksh way for ~ works"
else
echo "zsh/ksh does for ~ not work"
fi


if glob_filename_bash_old 'embedded blank' ; then
echo "bash version < 4.3 way works"
else
echo "bash version < 4.3 does not work"
fi

if glob_filename_ksh_zsh 'embedded blank' ; then
echo "zsh/ksh way works"
else
echo "zsh/ksh does not work"
fi



So how can I rewrite that function so it meets this goal? Ideal would be something that works in bash, ksh and zsh.

Thoughts?
0 new messages