0

I have a bash script that launches another bash script and needs to pass multiple parameters (which may contain spaces). In the launcher script I am defining the parameters as a single string, escaping any spaces as necessary. However I can't seem to get the parameters passed properly.

Here is my test setup to replicate the problem I am having:

test.sh

  
while [[ $# -gt 0 ]]; do
  echo "${1}"
  shift
done

launcher.sh

#!/bin/bash
args="arg1 arg2 arg\ 3 arg4"
./test.sh ${args}

Running test.sh directly from command line (./test.sh arg1 arg2 arg\ 3 arg4)

arg1
arg2
arg 3
arg4

Running launcher.sh

arg1
arg2
arg\
3
arg4

I've tried multiple variations of double quotes, read, IFS, etc, but I can't seem to get the results I am looking for. Any guidance would be appreciated.

bqq100
  • 55
  • 1
  • 5
  • Don't pass arguments as single string. Just pass it as multiple quoted separate arguments – anubhava Feb 03 '21 at 06:17
  • This is just to demo the issue. In the real launcher script the parameter string has a default value which I want the user to be able to override by doing a single read -p which is why I am storing the parameters as a single string. – bqq100 Feb 03 '21 at 06:26
  • See [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050), and specifically [**5. I'm constructing a command based on information that is only known at run time**](http://mywiki.wooledge.org/BashFAQ/050#I.27m_constructing_a_command_based_on_information_that_is_only_known_at_run_time) – David C. Rankin Feb 03 '21 at 06:33

2 Answers2

2

Use a bash array or xargs in launcher.sh:

#!/bin/bash

args=(arg1 arg2 "arg 3" arg4)

./test.sh "${args[@]}"

echo =======================

args="arg1 arg2 arg\ 3 arg4"

echo $args | xargs ./test.sh

Execution:

$ ./launcher.sh 
arg1
arg2
arg 3
arg4
=======================
arg1
arg2
arg 3
arg4
Rachid K.
  • 4,490
  • 3
  • 11
  • 30
  • Thanks, but in my actual script, args is being collected with a single read -p which returns a string. That is why in this demo script I stored it as a string. Is there anyway to cleanly convert the string into an array? – bqq100 Feb 03 '21 at 06:28
  • What about using xargs ? I am updating my answer... – Rachid K. Feb 03 '21 at 06:30
1

A friendly tip

After reading your entire question it seems you're trying to re-invent the wheel.

You should have tried read --help. It explains how to split user input into an indexed array.

Example

read -a args -p 'Input args: '

Full code example

test.sh

#!/bin/bash

for sArg in "$@" ;do
   echo "$sArg"
done

launcher.sh

#!/bin/bash

read -a args -p 'Input args: '
./test.sh "${args[@]}"
svin83
  • 239
  • 1
  • 4
  • 13
  • Thanks. I had tried using read -a based on other examples that I found but still couldn't get it to work. It looks like I I didn't have the "${args[@]}" syntax correct after the read. – bqq100 Feb 04 '21 at 02:56