bash ls: 无法访问文件 : 没有那个文件或目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14930479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:35:25  来源:igfitidea点击:

ls: cannot access file : No such file or directory

bashshellls

提问by Rudra

In the shell script, I will have to access the binary logs stored in /usr/local/mysql/data. but when I do this,

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

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

I get the below error :

我收到以下错误:

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

But when I manually enter the numbers in the range the shell scripts runs normally without error.

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

回答by jordanm

In bash, brace expansion occurs before variables are expanded. This means that you can not use variable inside of {}and get your expected results. I recommend using an array and a for loop:

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

回答by vonbrand

Try using seq(1):

尝试使用seq(1)

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

回答by Udo Klein

You want the files in the range 000002..000222

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

but because of the quotes you are asking for the file with the name

但由于引号,您要求使用名称的文件

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

I would use a shell loop: http://www.cyberciti.biz/faq/bash-loop-over-file/

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