Well you are close, but you have a few errors in the provided examples. Firstly you don't need the While
loop in either script as it does not serve a purpose in the code examples you provided so I omitted them from my examples.
Example 1
#!/bin/bash
external_function(){
echo "This is printed from the sourced script";
[ -e ./fifo1 ] && return $TRUE || return $FALSE
}
Example 2
#!/bin/bash
source ./test.sh
external_function && echo "the file exists" || echo "The file doesn't exist"
exit
What you are doing is using the . (source or dot operator)
which will read and execute commands from the filename argument in the current shell context.
Syntax
. filename [arguments]
source filename [arguments]
When a script is run using source it runs within the existing shell, any variables created or modified by the script will remain available after the script completes. In contrast if the script is run just as filename, then a separate subshell (with a completely separate set of variables) would be spawned to run the script.
This means you do NOT want to use the &
to fork the second script to a new process as it will never return to the main script.
Also I typically will put the code I wish to run in the second (sourced) script in a function. I think it makes it easier to read and you can use this to check return codes from the function which makes debugging much easier.
And lastly if [[ $(cat ./fifo1) = 0 ]]
is merely checking for existence as you are checking the exit status of the cat command. You can simply this with the line below:
[ -e / ] && return $TRUE || return $FALSE
-e
is a bash File Test Operator that checks for a FILE
's existence.
&&
is a bash Operator that will run the following command if the last command returned a successfully exit code (not zero)
||
is a bash Operator in that will run the following command if the last command returned an failed exit code (zero)
Further Reading:
I use this reference for bash alot and I think it is worth mentioning