相关疑难解决方法(0)

现在解析 GNU ls 的输出是否安全?

过去几十年来公认的观点是,解析ls( [1] , [2]的输出从来都不是一个好主意 ) 的输出从来都不是一个好主意。例如,如果我想将文件的修改日期及其名称保存到 shell 变量中,则这不是正确的方法:

\n
$ ls -l file\n-rw-r--r-- 1 terdon terdon 0 Aug 15 19:16 file\n$ foo=$(ls -l file | awk \'{print $9,$6,$7,$8}\')\n$ echo "$foo"\nfile Aug 15 19:16\n
Run Code Online (Sandbox Code Playgroud)\n

只要文件名稍有不同,该方法就会失败:

\n
$ ls -l file*\n-rw-r--r-- 1 terdon terdon 0 Aug 15 19:16 \'file with spaces\'\n$ foo=$(ls -l file* | awk \'{print $9,$6,$7,$8}\')\n$ echo "$foo"\nfile Aug 15 19:16\n
Run Code Online (Sandbox Code Playgroud)\n

如果文件的修改日期与今天不接近,情况会变得更糟,因为这可能会更改时间格式:

\n
$ ls -l\ntotal 0\n-rw-r--r-- 1 terdon terdon 0 Aug 15 19:21  file\n-rw-r--r-- 1 …
Run Code Online (Sandbox Code Playgroud)

ls shell text-processing filenames

25
推荐指数
2
解决办法
4643
查看次数

标签 统计

filenames ×1

ls ×1

shell ×1

text-processing ×1