在if语句(bash)中

时间:2019-06-17 18:38:02

标签: bash macos if-statement

我需要检查变量的值是否存在。这是从文本文件读取的。

基本上,我停留在的点line变量如下:location_of_folder=~/Desktop/folder\ with\ spaces

我需要检查location_of_folder=之后的路径是否存在。

这是我尝试过的:

foo="${line#'location_of_folder='}"
if ! [[ -d "${foo}" ]]
then
  echo 'This path exists.'
else
  echo 'This path does not exist.'
fi

if ! [[ -d "${line#'location_of_folder='}" ]]
then
  echo 'This path exists.'
else
  echo 'This path does not exist.'
fi

但是,两者都说该路径不存在,这确实是不正确的。

是的,在我正在读取的文本文件中,像这样:

location_of_folder=~/Desktop/folder\ with\ spaces

在OSX El Capitan 10.11.6下使用bash 3.2.57(1)-发行版。

谢谢。

1 个答案:

答案 0 :(得分:0)

这并不是真正的答案,但是注释很难格式化。这里有几个问题,下面的序列演示了其中的一些问题。请注意,这里有一些公然的坏习惯(不要使用eval,但是如果要将~扩展到路径,这实际上就是您所需要的)。

$ cat input
location_of_folder=~/Desktop/directory\ with\ spaces
location_of_folder=$HOME/Desktop/directory\ with\ spaces
$ while IFS== read -r name path; do if eval "test -d $path"; then echo "$path" exists; else echo "$path" does not exist; fi;  done < input
~/Desktop/directory\ with\ spaces exists
$HOME/Desktop/directory\ with\ spaces exists
$ while IFS== read name path; do if test -d "$path"; then echo "$path" exists; else echo "$path" does not exist; fi;  done < input
~/Desktop/directory with spaces does not exist
$HOME/Desktop/directory with spaces does not exist
$ while IFS== read name path; do if eval test -d "$path"; then echo "$path" exists; else echo "$path" does not exist; fi;  done < input
bash: test: too many arguments
~/Desktop/directory with spaces does not exist
bash: test: too many arguments
$HOME/Desktop/directory with spaces does not exist
$ while IFS== read name path; do if eval "test -d \"$path\""; then echo "$path" exists; else echo "$path" does not exist; fi;  done < input
~/Desktop/directory with spaces does not exist
$HOME/Desktop/directory with spaces exists 

好吧,我想这是一个答案,因为第一行似乎可以为您提供所需的信息。但是仅使用eval扩展~是一个糟糕的主意。