在bash中使用home字符(〜)检查目录是否存在失败

为什么以下bash检查目录是否失败?
if [ ! -d "~/Desktop" ]; then
   echo "DOES NOT EXIST"
   exit 1;
fi

〜/桌面确实存在.顺便说一句,这是在Mac上.

问题在于这种类型的脚本

read -p "Provide the destination directory: " DESTINATION

if [ ! -d $DESTINATION ]; then
    echo "\t'$DESTINATION' does not exist." >&2;
    exit 1;
fi
贾斯汀在他关于量子答案的第一个评论中澄清了他的问题.他正在使用read(或其他动态方法)读取一行文本,并希望扩展代字号.

问题变成“你如何对变量的内容进行波浪扩展?”

一般方法是使用eval,但它带有一些重要的警告,即变量中的空格和输出重定向(>).以下似乎对我有用:

read -p "Provide the destination directory: " DESTINATION

if [ ! -d "`eval echo ${DESTINATION//>}`" ]; then
    echo "'$DESTINATION' does not exist." >&2;
    exit 1;
fi

尝试使用以下每个输入:

~
~/existing_dir
~/existing dir with spaces
~/nonexistant_dir
~/nonexistant dir with spaces
~/string containing > redirection
~/string containing > redirection > again and >> again

说明

> ${mypath //>}剥离>在评估期间可能破坏文件的字符.
> eval echo …是实际的波浪扩展
> eval周围的双引号用于支持带空格的文件名.

作为对此的补充,您可以通过添加-e选项来改进UX以进行读取:

read -p "Provide the destination directory: " -e DESTINATION

现在,当用户键入波浪号和点击选项卡时,它将展开.但是,这种方法并不能取代上面的eval方法,因为扩展仅在用户点击选项卡时才会发生.如果他只输入〜/ foo并命中输入,它将保持为波浪号.

也可以看看:

> https://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...