我正在编写一个脚本,当用户登录并检查某个文件夹是否存在或符号链接损坏时会调用该脚本。(这是在Mac OS X系统上,但问题纯粹是bash)。
它不是很优雅,也不起作用,但是现在看起来像这样:
#!/bin/bash
# Often users have a messed up cache folder -- one that was redirected
# but now is just a broken symlink. This script checks to see if
# the cache folder is all right, and if not, deletes it
# so that the system can recreate it.
USERNAME=$3
if [ "$USERNAME" == "" ] ; then
echo "This script must be run at login!" >&2
exit 1
fi
DIR="~$USERNAME/Library/Caches"
cd $DIR || rm $DIR && echo "Removed misdirected Cache folder" && exit 0
echo "Cache folder was fine."
问题的症结在于波浪号扩展无法按我的意愿进行。
假设我有一个名为的用户george
,他的主文件夹为/a/path/to/georges_home
。如果在shell上键入:
cd ~george
它带我到适当的目录。如果输入:
HOME_DIR=~george
echo $HOME_DIR
它给了我:
/a/path/to/georges_home
但是,如果我尝试使用变量,它将无法正常工作:
USERNAME="george"
cd ~$USERNAME
-bash: cd: ~george: No such file or directory
我试过使用引号和反引号,但无法弄清楚如何使其正确扩展。我该如何工作?
附录
我只是想发布自己完成的脚本(真的,它不像上面的工作那样丑陋!),并说它似乎工作正常。
#!/bin/bash
# Often users have a messed up cache folder -- one that was redirected
# but now is just a broken symlink. This script checks to see if
# the cache folder is all right, and if not, deletes it
# so that the system can recreate it.
#set -x # turn on to help debug
USERNAME=$3 # Casper passes the user name as parameter 3
if [ "$USERNAME" == "" ] ; then
echo "This script must be run at login!" >&2
exit 1 # bail out, indicating failure
fi
CACHEDIR=`echo $(eval echo ~$USERNAME/Library/Caches)`
# Show what we've got
ls -ldF "$CACHEDIR"
if [ -d "$CACHEDIR" ] ; then
# The cache folder either exists or is a working symlink
# It doesn't really matter, but might as well output a message stating which
if [ -L "$CACHEDIR" ] ; then
echo "Working symlink found at $CACHEDIR was not removed."
else
echo "Normal directory found at $CACHEDIR was left untouched."
fi
else
# We almost certainly have a broken symlink instead of the directory
if [ -L "$CACHEDIR" ] ; then
echo "Removing broken symlink at $CACHEDIR."
rm "$CACHEDIR"
else
echo "Abnormality found at $CACHEDIR. Trying to remove." >&2
rm -rf "$CACHEDIR"
exit 2 # mark this as a bad attempt to fix things; it isn't clear if the fix worked
fi
fi
# exit, indicating that the script ran successfully,
# and that the Cache folder is (almost certainly) now in a good state
exit 0