简体   繁体   中英

Sourcing a script file in bash before starting an executable

I'm trying to write a bash script that "wraps" whatever the user wants to invoke (and its parameters) sourcing a fixed file just before actually invoking it.

To clarify: I have a "ConfigureMyEnvironment.bash" script that must be sourced before starting certain executables, so I'd like to have a "LaunchInMyEnvironment.bash" script that you can use as in:

LaunchInMyEnvironment <whatever_executable_i_want_to_wrap> arg0 arg1 arg2

I tried the following LaunchInMyEnvironment.bash:

#!/usr/bin/bash
launchee="$@"
if [ -e ConfigureMyEnvironment.bash ];
     then source ConfigureMyEnvironment.bash;
fi

exec "$launchee"

where I have to use the "launchee" variable to save the $@ var because after executing source, $@ becomes empty.

Anyway, this doesn't work and fails as follows:

myhost $ LaunchInMyEnvironment my_executable -h
myhost $ /home/me/LaunchInMyEnvironment.bash: line 7: /home/bin/my_executable -h: No such file or directory
myhost $ /home/me/LaunchInMyEnvironment.bash: line 7: exec: /home/bin/my_executable -h: cannot execute: No such file or directory

That is, it seems like the "-h" parameter is being seen as part of the executable filename and not as a parameter... But it doesn't really make sense to me. I tried also to use $* instead of $@, but with no better outcoume.

What I'm doing wrong?

Andrea.

您是否尝试在exec命令中删除双引号?

Try this:

#!/usr/bin/bash
typeset -a launchee
launchee=("$@")
if [ -e ConfigureMyEnvironment.bash ]; 
  then source ConfigureMyEnvironment.bash; 
fi 
exec "${launchee[@]}"

That will use arrays for storing arguments, so it will handle even calls like "space delimited string" and "string with ; inside"

Upd: simple example

test_array() { abc=("$@"); for x in "${abc[@]}"; do echo ">>$x<<"; done; } test_array "abc def" ghi

should give

>>abc def<<
>>ghi<<

You might want to try this (untested):

#!/usr/bin/bash
launchee="$1"
shift
if [ -e ConfigureMyEnvironment.bash ];
     then source ConfigureMyEnvironment.bash;
fi

exec "$launchee" $@

The syntax for exec is exec command [arguments] , however becuase you've quoted $launchee , this is treated as a single argument - ie, the command, rather than a command and it's arguments. Another variation may be to simply do: exec $@

Just execute it normally without exec

#!/usr/bin/bash
launchee="$@"
if [ -e ConfigureMyEnvironment.bash ];
     then source ConfigureMyEnvironment.bash;
fi

$launchee

Try dividing your list of argumets:

ALL_ARG="${@}"
Executable="${1}"
Rest_of_Args=${ALL_ARG##$Executable}

And try then:

$Executable $Rest_of_Args
(or exec $Executable $Rest_of_Args)

Debugger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM