我正在编写一个脚本,当用户登录时调用该脚本并检查某个文件夹是否存在或是否符号链接损坏. (这是在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,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
使用$(eval echo …):
michael:~> USERNAME=michael michael:~> echo ~michael /home/michael michael:~> echo ~$USERNAME ~michael michael:~> echo $(eval echo ~$USERNAME) /home/michael
所以你的代码应该是这样的:
HOMEDIR="$(eval echo ~$USERNAME)"