在bash中的测试语句中运行命令
发布时间:2020-12-16 01:46:47 所属栏目:安全 来源:网络整理
导读:我有一段代码来查找目录中的第一个文件: bash~ $( echo eval "ls | head -1" )arguprog.sh 然后将此片段添加到if语句中,以便在该文件为arguprog.sh时运行另一组命令: bash~ if [[ $( echo eval "ls | head -1" ) == "arguprog.sh" ]]; then echo "TRUE"; e
我有一段代码来查找目录中的第一个文件:
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! 有没有办法解决这个问题,同时仍然完全在测试块内进行字符串比较? 解决方法
首先,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.shnwith 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! 对此有扭曲的解决方法,但实际上,最好的方法就是我刚给你的方法. 完成! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |