1

I wrote a shell script to just check whether file exists or not. Below is the snapshot:

#!/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

It is saying syntax error:

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

what am I doing wrong? Please suggest.

2 Answers 2

1

Run your script in ksh cell or bash cell and modify this first line #!/bin/sh to #!/bin/ksh or #!/bin/bash Also modify your if condition like below else it will print both the statement as your else part is missing.

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

Also your if condition is not correct here you are checking whether file is not present or not but statement is file is already present See my modified script below and compare with you mistakes.

#!/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
Sign up to request clarification or add additional context in comments.

Comments

0

/bin/sh does not in general recognise functions defined with the function keyword. This is a keyword used by bash and ksh (and possibly by some other shells).

Your script with a function could be written

#!/bin/sh

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

file_status_check 'test.txt'

... but honestly, it would be enough with

#!/bin/sh

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

unless you need to do this for multiple files and need to provide the same output for all of them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.