Kin*_*ech 2 linux scripting bash shell-script stat
我正在使用脚本根据创建文件的年份复制一些文件,它适用于没有空格的文件,但对于有空格的文件,stats 命令有问题,例如我有这个文件: file with spaces.pdf
stat -c %y ./path/to/file\ with\ spaces.pdf|cut -d '-' -f 1
Run Code Online (Sandbox Code Playgroud)
返回年份,例如:2017
但是在脚本中使用时:
year=$(stat -c %y $pathfile | cut -d '-' -f 1)
Run Code Online (Sandbox Code Playgroud)
这似乎不是工作,如果我采取了以下输出:
echo "stat -c %y file | cut -d '-' -f 1"
Run Code Online (Sandbox Code Playgroud)
并在终端中复制它它确实有效,在所有情况下错误都是一样的,就像忽略文件名的这一部分with\ spaces.pdf
::
stat: cannot stat './path/to/file\': No such file or directory
Run Code Online (Sandbox Code Playgroud)
我试过在路径中添加引号,但它似乎不起作用:
year=$(stat -c %y "$pathfile" | cut -d '-' -f 1)
Run Code Online (Sandbox Code Playgroud)
我在某处看到我需要将统计信息放在一个函数中,我这样做了:
makestats () {
$(stat -c %y $1|cut -d '-' -f 1)
}
Run Code Online (Sandbox Code Playgroud)
但它似乎不起作用,如果你能给我你的帮助,我会得到同样的错误。
在 中引用您的变量bash
,不这样做会将变量中的单词拆分为单个标记,并且使用该变量的命令将在期望单个字符串时获得多个单词(请参阅shell 中的单词拆分)
year=$(stat -c %y "$pathfile" | cut -d '-' -f1)
Run Code Online (Sandbox Code Playgroud)
我想您的问题出在您"
与\
转义序列一起使用的变量中。你需要做任何一个。
pathfile="/path/to/file with spaces"
Run Code Online (Sandbox Code Playgroud)