用于检查文件的Shell脚本返回语法错误

时间:2018-05-18 09:20:26

标签: shell

我编写了一个shell脚本来检查文件是否存在。以下是快照:

#!/bin/sh
#version/300

file="test.txt"


  function file_status_check {
        if [ ! -f "$1" ]
        then
           echo  "file is already present"
        fi
           echo  "file is not present. Please create the file"
}
file_status_check $file

说语法错误:

testscript.sh: 7: testscript.sh: function: not found
file is already present
file is not present. Please create the file
testscript.sh: 13: testscript.sh: Syntax error: "}" unexpected
我做错了什么? 请建议。

2 个答案:

答案 0 :(得分:1)

ksh单元格或bash单元格中运行您的脚本并将第一行#!/bin/sh修改为#!/bin/ksh#!/bin/bash同时修改您的if条件,如下所示它将打印该声明,因为else部分缺失。

    if [ ! -f "$1" ]
    then
       echo  "file is already present"
    else
       echo  "file is not present. Please create the file"
    fi

此外你的if条件不正确你正在检查文件是否不存在但是语句是file is already present请参阅下面我修改过的脚本并与你的错误进行比较。

#!/bin/bash
#version/300

file="test.txt"

function file_status_check {
    if [-f "$1" ]
    then
       echo  "file is already present"
    else
       echo  "file is not present. Please create the file"
    fi
}

file_status_check $file

答案 1 :(得分:0)

/bin/sh通常不会识别使用function关键字定义的函数。这是bashksh(以及可能由其他一些shell)使用的关键字。

可以编写带有函数的脚本

#!/bin/sh

file_status_check () {
    if [ -f "$1" ]; then
        echo 'file present'
    else
        echo 'file not present'
    fi
}

file_status_check 'test.txt'

......但老实说,用

就足够了
#!/bin/sh

if [ -f 'test.txt' ]; then
    echo 'file present'
else
    echo 'file not present'
fi

除非您需要为多个文件执行此操作,并且需要为所有文件提供相同的输出。