Home > Back-end >  Use spaces in parameter used in script called by a command
Use spaces in parameter used in script called by a command

Time:02-01

I need to run a Bash command with a script calling parameters: comm1 ./script.sh param1 param2 param3. Script includes this: timeout 10 bash -c " comm2 ./param1.param3". It indicates that param1 file is in the current directory.

And it works as long as param1 is a single word. But I need it to be a file name which can have spaces. So command should be: comm1 ./script.sh "param1\ with\ space" param2 param3 . No dot and extension in file name, just spaces are problem and maybe brackets.

I don't know how to modify param1 to be able to use spaces in this case, and if script should also be modified. Thanks for help.

CodePudding user response:

Instead of trying to quote and escape the parameters, send the parameters to bash -c.

timeout 10 bash -c 'comm2 "$@"' bash "$1" "$2"

This will set $0 to "bash" and the first two parameters to the values of the first two positional parameters of the script.

CodePudding user response:

I'm a bit unsure on the exact reason to call bash first.

The easiest answer is to simply skip the bash call:

timeout 10 comm2 "./param with.spaces" param2

If you want to reuse the logic in several places, make a function.

timesup() { timeout 10 "$@" ;}

timesup comm2 "./param with.spaces" param2

whatever command you throw, the function will parse it the same way

If you really need to call bash first for whatever reason, you could mix quotation:

timeout 10 bash -c "comm2 './param with.spaces' param2"
  •  Tags:  
  • Related