2

This is my function

  validateFile()
  {
    echo "$1" | grep '.zip$' > /dev/null 
    if [ $? -eq 0 ]
    then
        return 1
    else
        return 0
     fi 
  }
  printf "\n Enter Source File1 Path: "
  read file1
  res=$(validateFile $file1);
  echo "$res"

But nothing store in **"res"** store nothig

validateFile function verify that file is zip file or not if yes then return 2 else 0.And returned value stored in res variable. But issue is no value store in res variable.

0

4 Answers 4

2

Although shell script provides a return statement, the only thing you can return with, is the function's own exit status (a value between 0 and 255, 0 meaning "success"). Best way to return a value is to echo the same, something like below:

validateFile()
  {
    echo "$1" | grep '.zip$' > /dev/null 
    if [ $? -eq 0 ]
    then
        echo 1
    else
        echo 0
    fi 
  }
printf "\n Enter Source File1 Path: "
read file1
res=$(validateFile $file1);
echo "$res"
Sign up to request clarification or add additional context in comments.

Comments

1

What you want is maybe

validateFile()
  {
    echo "$1" | grep '.zip$' > /dev/null 
    if [ $? -eq 0 ]
    then
        # return appropriate value
        return 1
    else
        return 0
    fi 
  }
printf "\n Enter Source File1 Path: "
read file1
# call function
validateFile $file1
# use return code
res=$?
echo "$res"

2 Comments

IMHO, return should be reserved for the exit code of the function and echo should be used to return values.
Where possible and no exit code is otherwise needed, the assignment of an exit code looks more elegant than the $( ) construction catching the echo output. If non-recursive there still is the possibility to use a variable to return a value solving all problems at once.
0

$(...) invokes a subshell and captures its standard output. So you can do one of these two things:

foo() {
  fooresult=1
}
foo
echo $fooresult

or this:

foo() {
  echo 1
}
fooresult=$(foo)
echo $fooresult

Comments

0
validateFile()
{
    echo "$1" | grep '.zip$' > /dev/null 
    if [ $? -eq 0 ]
    then
        echo 1
    else
        echo 0
    fi 
}
printf "\n Enter Source File1 Path: "
  read file1
  res=$(validateFile $file1);
  echo "$res"

1 Comment

Although this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.