ls:无法访问文件:没有这样的文件或目录

时间:2013-02-18 06:13:14

标签: bash shell ls

在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脚本正常运行而没有错误。

3 个答案:

答案 0 :(得分:3)

在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[@]}"

答案 1 :(得分:2)

尝试使用seq(1)

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

答案 2 :(得分:0)

您希望文件的范围为000002..000222

但由于引号,您要求的文件名为

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

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