【问题标题】:Bash Script compare strings and variable in an if statementBash 脚本在 if 语句中比较字符串和变量
【发布时间】:2014-10-09 20:43:53
【问题描述】:

我正在尝试获取一个变量来与一个字符串进行比较,然后执行某些操作并继续下一个操作,但是当我在调试模式下查看它时,该变量仅显示为 ''里面什么都没有。

#!/bin/bash
echo -e "Enter the name of the document you wish to edit:\c"
read dname
CTYPE= file "$dname" | cut -d\  -f2
echo $CTYPE
VAR="ASCII"
VAR2="cannot"
if [ "$CTYPE" == "$VAR" ]
then
    vi $dname                       
fi

我得到这个结果:

+ VAR=ASCII
+ VAR2=cannot
+ '[' '' == ASCII ']'

'' 是空的,即使我 echod 并看到它不是空的。

我也尝试过像这些其他方式一样,并得到相同或相似的无效结果:

CTYPE= file "$dname" | cut -d\  -f2
if [ "$CTYPE" == "$VAR" ]

ctype= file "$dname" | cut -d\  -f2
if [ $ctype = "ASCII" ]

ctype= file "$dname" | cut -d\  -f2
if [ "$ctype" = "ASCII" ]   

ctype= file "$dname" | cut -d\  -f2
if [ "$ctype" == "ASCII" ]

不知道我错过了什么,我已经阅读了很多帖子,我不知道从哪里开始。谢谢!

【问题讨论】:

    标签: string bash variables comparison


    【解决方案1】:

    CTYPE 有错误:

    CTYPE=$(file "$dname" | cut -d\  -f2)
    

    = 和作业之间不能有任何个空格。此外,您希望从file "$dname" | cut -d\ -f2 返回,因此您必须将其括在$() 或反引号中。

    【讨论】:

      【解决方案2】:

      当你运行这个命令时:

      d= date
      

      bash 这样做:在date 命令的持续时间内设置一个环境变量d(值为空字符串)only。这在here有大量文档。

      正如David 告诉您的,要捕获命令的输出,您需要

      d=$(date)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-17
        • 1970-01-01
        • 2020-08-07
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多