In a bash script, we can escape spaces with \
. Is there any way to do the same from code?
$ a=hello\ world
$ echo $a
hello world
$ b=${a:?} # ? used as dummy; it will not work
$ echo $b
hello\ world
caller.bash
#!/bin/bash
name=$1
if [[ -n $name ]]; then
where_query="--where name $name"
fi
mycommand $where_query
mycommand, an external program, we cannot modify. Dummy code added only for illustration purposes.
#!/bin/bash
for i in "${@}"
do
echo "$i"
done
Actual
$ caller.bash "foo bar"
--where
name
foo
bar
Expected
$ caller.bash "foo bar"
--where
name
foo bar
What you are trying to do is impossible with simple string variables. You are trying to pass either three parameters or none to the "external program" mycommand. You should use bash arrays. Please try the following:
caller.bash:
Your scripts have also quoting errors. You should check all your scripts at https://www.shellcheck.net/ before trying to use them at all.