2015-05-25 108 views
0

我想查看一个文件夹是否存在。在脚本文件中如果我使用:在shell脚本中使用存在命令的路径变量

#!/bin/bash 

batch_folder=~/Desktop/ 
if [ -d $batch_folder ] 
then 
    echo "Dir exists." 
else 
    echo "Dir doesn't exists." 
fi 

我得到的结果是相应的回声。但是当我用read命令提示输入路径时,即使确实存在,每次都会发现该目录不存在。这是我的脚本:

#!/bin/bash 

read -e -p "Batch folder location: " batch_folder 
if [ -d $batch_folder ] 
then 
    echo "Dir exists." 
else 
    echo "Dir doesn't exists." 
fi 

我也试过在if声明可变"$batch_folder"${batch_folder}"${batch_folder}"但这些作品的使用。

我知道问题出在如何read命令保存的变量,因为在我的第一个例子,如果我设置batch_folder='~/Desktop/'我得到了相同的结果与read命令。

回答

3

我打算假设您正在输入th在提示符处出现。 ~的扩展是在脚本令牌上发生的shell功能,而不是通常的参数或输入。

您可以expand it manually

batch_folder="${batch_folder/#\~/$HOME}" 
0

首先,引用变量:

if [ -d "$batch_folder" ] 

其次,评估变量中的内容(扩展字符像~):

... 
eval batch_folder="${batch_folder}" 
if [ -d "$batch_folder" ] 
... 

的第一句话将修复为迪尔斯问题第二个将解决包含~等dirs的问题。

+1

或者使用'[[]]'代替,则变量不需要被引用。 – cdarke

相关问题