ls: invalid option – ‘j’

1
2
3
4
5
6
7
8
$ ls

0n5whdeZ0ow-download.jpg A-McbCSin6w-download.jpg G1vKK6L7Ep0-download.jpg .....
-jGGcAqIBms-download.jpg -pahtnAMuFo-download.jpg

$ ls *.jpg
ls: invalid option -- 'j'
Try 'ls --help' for more information.

这个简单的命令执行失败了,期望 shell 扩展 * 找出所有 jpg 图像,也没有传入 -j 作为 option 选项,很是奇怪,通过 bing 找到了答案,百度真的是不适合程序员…..

StackExchange ls invalid option 中的问题类似,原因是有个图像文件开头是 - (-jGGcAqIBms-download.jpg),被当作 ls 的 option 选项了….

man bash

A -- signals the end of options and disables further option processing. Any arguments after the – are treated as file‐ names and arguments. An argument of - is equivalent to –.

解决上述问题的办法:

  1. 使用 --
1
ls -- *.jpg
  1. 生产脚本使用 find + xargs,更保险
1
2
# -name选项指定了待查找文件名的模式。这个模式可以是通配符,也可以是正则表达式
find . -type f -name '*.jpg' -print0 | xargs -0 -n 1 command
  1. 修改文件名,避免此种情况发生
1
for img in $(find . -maxdepth 1 -type f  ! -iname 'unsplash*.jpg'); do new=unsplash_${img##*/}; sudo mv "$img" "$new"; done;