Home > OS >  How can I call an external bash function with parameters in an if condition
How can I call an external bash function with parameters in an if condition

Time:09-17

I am trying to call an external bash script in an if condition in my main script. The code of the external script IsArchive:

#!/bin/bash
STR="$1"

if [[ "$STR" ==  *".zip"* ]] || [[ "$STR" ==  *".iso"* ]] || [[ "$STR" ==  *".tar.gxz"* ]] || [[ "$STR" ==  *".tar.gx"* ]] || [[ "$STR" ==  *".tar.bz2"* ]] || \
   [[ "$STR" ==  *".tar.gz"* ]] || [[ "$STR" ==  *".tar.xz"* ]] || [[ "$STR" ==  *".tgz"* ]] || [[ "$STR" ==  *".tbz2"* ]]
then
        return 0
else 
        return 1
fi

and I try calling it in my main script as:

elif [[ $Option = "2" ]]
then
                if IsArchive "$SourcePath";
                then
                        less -1Ras "$SourcePath" | tee "$OutputFilePath"

                #if file is not an archive
                else
                        ls -1Rasl "$SourcePath" | tee "$OutputFilePath"
                fi

when I execute the main script I receive the Error: ./script: line 61: IsArchive: command not found

CodePudding user response:

You just need to make sure that the script is in your PATH. Either that, or reference it with either a full path or a relative path. Perhaps you just need to write:

if ./IsArchive "$SourcePath"; then ...

But there are several issues with IsArchive. You cannot return except from a function, so you probably want to use exit 0 and exit 1 instead of return. You probably don't want to consider a name like foo.zipadeedoodah to be an archive, but *".zip"* will match that, so you should probably remove the trailing *. It would be simpler to write it with a case statement:

#!/bin/bash

case "$1" in
*.zip|*.iso|*.tar.gxz|*.tar.gx|*.tar.bz2| \
*.tar.gz|*.tar.xz|*.tgz|*.tbz2) exit 0;;
*) exit 1;;
esac
  • Related