0

I am trying to learn and write Bash scripts. The problem I am facing is to execute a command with parameters including spaces stored in a variable.

Let me give you a small example. A simple script contains a single line to print the parameter passed:

test.sh

#!/bin/bash
 
echo $1

If I run ./test.sh "Abcd Efgh" from the bash shell, it successfully prints Abcd Efgh

But if I put the command in a variable comm='./test.sh "Abcd Efgh"' and then run $comm, it print "Abcd

Could you please help me to solve this so that I can print Abcd Efgh in the second case as well? Thanks in advance. -ADR

Barmar
  • 741,623
  • 53
  • 500
  • 612
ADR
  • 1
  • 1
  • Escaping in bash will drive you batty. Better to use `echo $*` in the script and skip the quoting. – Tim Roberts Aug 12 '23 at 05:05
  • 1
    Don't try to put commands in variables, it's an invitation to all sorts of problems and confusion (see [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050)). Variables are for storing *data* not executable code or shell syntax. Use functions for storing executable code. – Gordon Davisson Aug 12 '23 at 05:32
  • @TimRoberts Using `$*` and skipping proper quoting is an open invitation to a *different* bunch of problems. Quote properly, including putting double-quotes around variable references (see ["When should I double-quote a parameter expansion?"](https://stackoverflow.com/questions/55023461/when-should-i-double-quote-a-parameter-expansion)), and you almost always want `"$@"` instead of anything involving `$*`. BTW, [shellcheck.net](https://www.shellcheck.net) is good at spotting many common mistakes about things like this. – Gordon Davisson Aug 12 '23 at 05:37

0 Answers0