1

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.

Hiren
  • 441
  • 1
  • 5
  • 11

4 Answers4

1

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"
Dummy00001
  • 15,836
  • 5
  • 37
  • 58
Supratim Das
  • 193
  • 1
  • 1
  • 8
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"
Stefan Hegny
  • 2,037
  • 4
  • 20
  • 24
  • IMHO, `return` should be reserved for the *exit code* of the function and `echo` should be used to return values. – Patrick Trentin Jun 17 '16 at 11:05
  • 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. – Stefan Hegny Jun 17 '16 at 20:01
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
Amadan
  • 179,482
  • 20
  • 216
  • 275
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"
Hiren
  • 441
  • 1
  • 5
  • 11
  • 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. – Toby Speight Jun 17 '16 at 10:34