-1

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

ma yoko
  • 1
  • 1

1 Answers1

1

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
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • ./IsArchive worked for me. Also the exit/return issue was a thing I didn't now yet. Thank you! I just wondered why I need to write ./IsArchive when I call another external script (not in an if statement this time) in my main script which I can use by just calling it by it's name (it is not in my $PATH variable). – ma yoko Sep 11 '21 at 12:25
  • @mayoko The `if` shouldn't make any difference. The other call must be either in your PATH or is a function. – William Pursell Sep 11 '21 at 12:28
  • Yes you are right. I guess I should take a short break from coding ... Thanks anyway :) – ma yoko Sep 11 '21 at 12:31
  • @mayoko There's a potential problem with using `./IsArchive` -- it looks for the IsArchive script in the current working directory, which is not generally the same directory the main script is in (it's inherited from whatever shell/other program ran the main script). If you want it to work when run from other directories, you need to [figure out what directory the main script is in](https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel). – Gordon Davisson Sep 11 '21 at 17:49