Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: problem running command with quotes

Tags:

bash

In answering another question I created the following script bash script:

#!/bin/bash

files1=( file1.txt file2.txt file3.txt )
files2=( file1_.txt file2_.txt file3_.txt )

cmd="vim -c 'set diffopt=filler,vertical' -c 'edit ${files1[0]}' -c 'diffsplit ${files2[0]}' "
echo $cmd
for i in {1..2}; do
  cmd="${cmd} -c 'tabe ${files1[i]}' -c 'diffsplit ${files2[i]}' "
done

#$cmd
echo $cmd

the problem is that if I try to run

$cmd

in the end of the script I get errors, but if I just use echo $cmd and then copy and paste in the command line it works just fine.

Any ideas what I am doing wrong?

Thanks.

like image 691
skeept Avatar asked Jan 21 '23 03:01

skeept


2 Answers

Use:

eval $cmd

So that the variables within the expression are expanded before execution.

like image 162
dogbane Avatar answered Jan 22 '23 17:01

dogbane


BASH FAQ entry #50: "I'm trying to put a command in a variable, but the complex cases always fail!"

like image 25
Ignacio Vazquez-Abrams Avatar answered Jan 22 '23 18:01

Ignacio Vazquez-Abrams