繁体   English   中英

bash中的逻辑表达式

[英]logical expression in bash

该脚本的目的是 go 文件包含目录名称列表和 append 到不存在的其他文件目录名称。

#!/bin/bash
FILES="list.txt"
2nd_file="2nd_list.txt"
for f in $FILES
do
    # if  backup dir exists, read next dir
if [ /bin/grep -q $f $2nd_file ]
then
    echo "Skiping $f file..."
    continue  # read next file
fi
    # we are hear means no file exists
    echo "$f" >>$2nd_file
done

我在 if 表达式中遇到错误。

我了解您的回答并更改了脚本:

 #!/bin/bash
 FILES="list.txt"
 2nd_file="2nd_list.txt"
 for f in $FILES
 do
        # if  backup dir exists, read next dir
 /bin/grep -q $f $2nd_file
 if [ $? -eq 0 ]
 then
    echo "Skiping $f file..."
    continue  # read next file
fi
    # we are hear means no dir exists
     echo "$f" >>$2nd_file
done

但是现在一个小问题是脚本不会从 FILES 中读取目录名

Output 是:

 Skiping list.txt file...

你的 if 表达式应该是:

if  /bin/grep -q $f $2nd_file

不带方括号

在您编辑帖子时已编辑:

你的脚本应该是:

#!/bin/bash
FILES="list.txt"
2nd_file="2nd_list.txt"
for f in $(cat $FILES) # see the modification
do
    # if  backup dir exists, read next dir
if /bin/grep -q $f $2nd_file # see the modification
then
    echo "Skiping $f file..."
    continue  # read next file
fi
    # we are hear means no file exists
    echo "$f" >>$2nd_file
done

我所做的修改是:

  • 在“for”中:您需要 $FILE 存档的内容,而不是字符串“list.txt”($FILES 变量的值),因此您必须使用cat或“<”转储这些内容(即: while read f; do... ; done < $FILES )

  • 在 if 语句中:你必须评估一个命令。 命令是你 grep。 如果 grep 返回 0 那么你的“如果”的东西就会完成; 任何其他返回值都将跳过您的 if 语句。 (这就像您对退货状态的无用检查,但效率更高)

[是一个命令。 如果您尝试使用grep作为命令,请不要使用[

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM