gpt4 book ai didi

bash - 在 bash 的测试语句中运行命令

转载 作者:行者123 更新时间:2023-11-29 09:19:32 25 4
gpt4 key购买 nike

我有一段代码可以找到目录中的第一个文件:

bash~> $( echo eval "ls | head -1" )
arguprog.sh

此片段随后被添加到 if 语句中,以在该文件为 arguprog.sh 时运行一组不同的命令:

bash~>  if [[ $( echo eval "ls | head -1" ) == "arguprog.sh" ]]; then echo "TRUE"; else echo "FALSE"; fi;
FALSE

但是这不是我想要的。即使第一个文件是 arguprog.sh,它也会返回 FALSE!

有没有办法解决这个问题,同时仍然完全在测试 block 内进行字符串比较?

最佳答案

首先,eval 是邪恶的,尤其是在不需要它的时候。在您的情况下,eval不需要的!

将您展示的编码恐惧替换为:

ls | head -1

并将其包含在您的测试语句中:

if [[ $(ls | head -1) = "arguprog.sh" ]]; then echo "TRUE"; else echo "FALSE"; fi

但这是错误和错误的(见下文)。

现在更一般:不解析 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

请注意您的方法,解析 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!

有一些扭曲的解决方法,但实际上,最好的方法是我刚刚给你的那个。

完成!

关于bash - 在 bash 的测试语句中运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14071586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com