How to import shell functions from one file into another? -


i have shell script:

#!/bin/bash  export ld=$(lsb_release -sd | sed 's/"//g') export arch=$(uname -m) export ver=$(lsb_release -sr)  # load test function /bin/bash -c "lib/test.sh"  echo $ver distros=('arch' 'centos' 'debian' 'fedora' 'gentoo') in "${distros[@]}"   i=$(echo $i | tr '[:upper:]' '[:lower:]') # convert distro string lowercase   if [[ $ld == "$i"* ]];     ./$arch/${i}.sh   fi done 

as can see should run shell script, depending on architecture , os run on. should first run script lib/test.sh before runs architecture , os-specific script. lib/test.sh:

#!/bin/bash  function comex {   $1 >/dev/null 2>&1 } 

and when run on x86_64 arch linux x86_64/arch.sh script:

#!/bin/bash  if comex atom;   printf "atom installed!" elif comex git;   printf "git installed!" fi 

it returned output:

rolling ./x86_64/arch.sh: line 3: comex: command not found ./x86_64/arch.sh: line 5: comex: command not found 

so comex shell function not correctly loaded time x86_64/arch.sh script run. hence confused , wondering need in order correctly define comex function such correctly loaded in architecture- , os-dependent final script.

i have tried using . "lib/test.sh" instead of /bin/bash -c "lib/test.sh" , received exact same error. have tried adding . "lib/test.sh" loop, before ./$arch/${i}.sh line. failed, returning same error.

brief answer: need import functions using . or source instead of bash -c:

# load test function source "lib/test.sh" 

longer answer: when call script bash -c, child process created. child process sees exported variables (including functions) parent process. not vice versa. so, script never see comex function. instead need include script code directly in current script , using . or source commands.


part 2. after "sourced" lib/test.sh, main script able use comex function. arch scripts won't see function because not exported them. need export -f comex:

#!/bin/bash  function comex {   $1 >/dev/null 2>&1 } export -f comex 

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -