【问题标题】:Space in directory name crashing .sh - use "usebackq"?目录名称中的空格崩溃 .sh - 使用“usebackq”?
【发布时间】:2014-11-15 09:19:55
【问题描述】:
dir1='/d/Dropbox/PhD/Experimental Design/APS/Processed_and_Graphed/InvariantQ'
echo $dir1

for f in A*.xlsx
do
   str2=${f%?????}
   if [[ ! -d $dir1/$str2 ]]; then
      mkdir $dir1/$str2
   else
      echo "Directory" $dir1/$str2 "already exists, directory not created"
   fi
   if [[ ! -f $dir1/$str2/$f ]]; then
      mv -v $f $dir1/$str2
   else
      echo "File" $dir1/$str2/$f "already exists, file not copied"
   fi
done

我正在尝试运行以下脚本,但是当它尝试 mkdir $dir1/$str2 时,它会创建:

/d/Dropbox/PhD/Experimental

并返回错误:

创建目录'/d/Dropbox/PhD/Experimental':文件存在

创建目录'Design/APS/Processed_and_Graphed/InvariantQ':没有这样的文件或目录

我已经尝试用双引号对目录名称进行编码,或者在“实验设计”中的空格前使用“\”,但是这两种方法似乎都不起作用......这似乎可以在批处理文件中使用“usebackq” - 有没有办法在 Windows 的 GitBash 中做到这一点?如果是这样,它将在我的代码中应用到哪里?

另外,有人知道为什么在这里使用“[[”测试语句有效,而单个“[”无效?

【问题讨论】:

标签: bash unix directory space git-bash


【解决方案1】:

引用您的变量以防止在展开时分词。

dir1='/d/Dropbox/PhD/Experimental Design/APS/Processed_and_Graphed/InvariantQ'
echo "$dir1"

for f in A*.xlsx
do
   str2=${f%?????}
   if [[ ! -d $dir1/$str2 ]]; then
      mkdir "$dir1/$str2"
   else
      echo "Directory $dir1/$str2 already exists, directory not created"
   fi
   if [[ ! -f $dir1/$str2/$f ]]; then
      mv -v "$f" "$dir1/$str2"
   else
      echo "File $dir1/$str2/$f already exists, file not copied"
   fi
done

它适用于[[,因为这是 shell 语法,而不是普通命令。它专门识别变量并且不对它们进行拆分。这与它允许您使用 < 等运算符而不引用它们的原因相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多