Finding script file in bash before running executable
I am trying to write a bash script that wraps whatever the user wants to call (and its parameters) to find a fixed file just before calling it.
To clarify: I have a "ConfigureMyEnvironment.bash" script that needs to be sent before some executables are run, so I would like to have a "LaunchInMyEnvironment.bash" script that you can use both 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 "lockchee" variable to save $ @ var , because after executing the source, $ @ becomes empty.
Anyway, it doesn't work and doesn't work like this:
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 that the "-h" option is treated as part of the executable filename, not as a parameter ... But it doesn't make sense to me. I also tried using $ * instead of $ @ , but without the best outcoume.
What am I doing wrong?
Andrea.
source to share
Try the following:
#!/usr/bin/bash
typeset -a launchee
launchee=("$@")
if [ -e ConfigureMyEnvironment.bash ];
then source ConfigureMyEnvironment.bash;
fi
exec "${launchee[@]}"
This will use arrays to store the arguments, so it will even handle calls like "space delimited string" and "string with; inside"
Update: simple example
test_array() { abc=("$@"); for x in "${abc[@]}"; do echo ">>$x<<"; done; }
test_array "abc def" ghi
should give
>> abc def << >> ghi <<
source to share
You might want to try this (untested) one:
#!/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, as you quoted $launchee
, this is treated as a single argument, i.e. command, not command and arguments. Another option could be simply:exec $@
source to share