【问题标题】:ls: cannot access file : No such file or directoryls: cannot access file : 没有这样的文件或目录
【发布时间】:2013-02-18 06:13:13
【问题描述】:

在 shell 脚本中,我必须访问存储在 /usr/local/mysql/data 中的二进制日志。 但是当我这样做时,

STARTLOG=000002
ENDLOG=000222
file=`ls -d /usr/local/mysql/data/mysql-bin.{$STARTLOG..$ENDLOG}| sed 's/^.*\///'`
echo $file

我收到以下错误:

ls: cannot access /usr/local/mysql/data/mysql-bin.{000002..000222}: No such file or directory. 

但是当我手动输入范围内的数字时,shell 脚本会正常运行而不会出错。

【问题讨论】:

  • 你真的有文件mysql-bin.{000002..000222} 吗?我认为没有。
  • 如何启动脚本?看来您是通过 sh 启动它,而不是 bash|zsh
  • 我用 bash 启动它,但它仍然给我同样的错误。
  • 当我直接在大括号内输入数字时,我能够获取这些文件,但当我使用变量名输入时,我无法获取这些文件。

标签: bash shell ls


【解决方案1】:

在 bash 中,大括号扩展发生在变量扩展之前。这意味着您不能在 {} 中使用变量并获得预期的结果。我建议使用数组和 for 循环:

startlog=2
endlog=222
files=()

for (( i=startlog; i<=endlog; i++ ));
   fname=/usr/local/mysql/data/mysql-bin.$(printf '%06d' $i)
   [[ -e "$fname" ]] && files+=("${fname##*/}")
done

printf '%s\n' "${files[@]}"

【讨论】:

    【解决方案2】:

    尝试使用seq(1)

    file=`ls -d $(seq --format="/usr/local/mysql/data/mysql-bin.%06.0f" $STARTLOG $ENDLOG) | sed 's/^.*\///'`
    

    【讨论】:

      【解决方案3】:

      您想要 000002..000222 范围内的文件

      但由于引号,您要求具有名称的文件

      /usr/local/mysql/data/mysql-bin.{000002..000222}
      

      我会使用 shell 循环:http://www.cyberciti.biz/faq/bash-loop-over-file/

      【讨论】:

      • 是的,我想访问该范围内的所有文件。
      • 不,这是由于使用了变量。 bash 规则相当临时。
      • 链接指南中存在错误。
      猜你喜欢
      • 2017-02-10
      • 1970-01-01
      • 2013-03-31
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多