bash - Passing a string value will fail to find the file -
i write shell try collect file file path current directory if exists:
collect_file() { fpath=$1 echo $fpath if [ -e $fpath ]; fname=`basename $fpath` `cp $1 $fname` retval=$? if [ $retval == 0 ]; echo "collect file '$fpath'" else echo "error: fail copy file '$fpath'" fi else echo "error: file '$fpath' not found" fi } now, if pass bare value ~/.gitconfig, succeed, when pass string value "~/.gitconfig", fail.
collect_file ~/.gitconfig # succeed copy file collect_file "~/.gitconfig" # fail shows:
# results bare value /users/xaree/.gitconfig collect file '/users/xaree/.gitconfig' # results string value ~/.gitconfig error: file '~/.gitconfig' not found why , how can fix it?
the following refers file in user's home directory:
~/.gitconfig by contrast, following refers file in directory named ~:
"~/.gitconfig" ~/ interpreted home directory when shell performs tilde expansion. shell perform tilde expansion when ! unquoted. if string quoted, ~ means ~ , nothing else.
examples
observe tilde expansion performed 1 of following 3 statements:
$ echo "~/.bashrc" ~/.bashrc $ echo ~"/.bashrc" ~/.bashrc $ echo ~/".bashrc" /home/john1024/.bashrc forcing tilde expansion
tilde expansion, implemented shell, offers many features many special cases. force general tilde expansion using eval introduce many security issues. basic case, however, can safely replace ~/ in variable $home/ follows:
fpath="${fpath/~\//$home\/}" a problem above replace first occurrence of ~/ if string not start ~/. avoid that, can use:
[ "${fpath#\~/}" != "$fpath" ] && fpath="${fpath/~\//$home\/}" this tests sure string starts ~/ before makes substitution.
Comments
Post a Comment