我有一段代码来查找目录中的第一个文件:
bash~> $( echo eval "ls | head -1" )
arguprog.sh
Run Code Online (Sandbox Code Playgroud)
然后将此片段添加到if语句中,以便在该文件为arguprog.sh时运行另一组命令:
bash~> if [[ $( echo eval "ls | head -1" ) == "arguprog.sh" ]]; then echo "TRUE"; else echo "FALSE"; fi;
FALSE
Run Code Online (Sandbox Code Playgroud)
然而,这不是我想要的.即使第一个文件是arguprog.sh,它也返回FALSE!
有没有办法解决这个问题,同时仍然完全在测试块内进行字符串比较?
首先,eval是邪恶的,特别是当它不需要时.对你来说,eval是不是需要!
用以下内容替换您显示的编码恐怖:
ls | head -1
Run Code Online (Sandbox Code Playgroud)
并将其包含在您的测试语句中:
if [[ $(ls | head -1) = "arguprog.sh" ]]; then echo "TRUE"; else echo "FALSE"; fi
Run Code Online (Sandbox Code Playgroud)
但这是错误的和破坏的(见下文).
现在更通用的东西:不要解析输出ls.如果要在当前目录中找到第一个文件(或目录或...),请使用globs和此方法:
shopt -s nullglob
files=( * )
# The array files contains the names of all the files (and directories...)
# in the current directory, sorted by name.
# The first one is given by the expansion of "${files[0]}". So:
if [[ "${files[0]}" = "arguprog.sh" ]]; then echo "TRUE"; else echo "FALSE"; fi
Run Code Online (Sandbox Code Playgroud)
请注意您的方法,解析ls是错误的.看:
$ # Create a new scratch dir
$ mkdir myscratchdir
$ # Go in there
$ cd myscratchdir
$ # touch a few files:
$ touch $'arguprog.sh\nwith a newline' "some other file"
$ # I created 2 files, none of them is exactly arguprog.sh. Now look:
$ if [[ $(ls | head -1) = "arguprog.sh" ]]; then echo "TRUE"; else echo "FALSE"; fi
TRUE
$ # HORROR!
Run Code Online (Sandbox Code Playgroud)
对此有扭曲的解决方法,但实际上,最好的方法就是我刚给你的方法.
完成!
| 归档时间: |
|
| 查看次数: |
1753 次 |
| 最近记录: |