0

I am trying to copy an entire script, not the script output but the entire script as a text line inside a file named test.sh. I am using another script to execute this so that is why I didn't use a text editor like vi.

I can't use echo "" or echo '' because the script string contains double quotes and single quotes inside.

What I used and it failed was:

echo "rm disktemp;./xpinfo -i|awk '{print $1}'|grep rhdisk|sed 's!/dev/r!!'>disktemp;for i in $(cat disktemp);do ./xpinfo -i|grep $i|sed 's!/dev/r!!'|awk '{print $6","$1'};done" > test.sh

Is there any way to do this?

  • Your attempt failed because double quoted strings will undergo parameter expansion, and the `$1` and such were expanded to nothing. It's possible but bothersome to use echo + single quotes, you should definitely follow Anubis' link – Aaron Apr 18 '19 at 12:50
  • Try $'' ksh93 have (might bash as well) this feature so quoting can be nested. – lw0v0wl Apr 18 '19 at 14:12

2 Answers2

1

Extended quoting

$'' $""

echo $'rm disktemp;./xpinfo -i|awk \'{print $1}\'|grep rhdisk|sed \'s!/dev/r!!\'>disktemp;for i in $(cat disktemp);do ./xpinfo -i|grep $i|sed \'s!/dev/r!!\'|awk \'{print $6","$1\'};done'

Output:

rm disktemp;./xpinfo -i|awk '{print $1}'|grep rhdisk|sed 's!/dev/r!!'>disktemp;for i in $(cat disktemp);do ./xpinfo -i|grep $i|sed 's!/dev/r!!'|awk '{print $6","$1'};done

You need to escape every quote with \ unfortunately to preserve them in the output. It better to escape all, but as you can see below it is enough only the one that used for $'' or $"":

echo $'This is a text \'single\' and "double" quote in it.'
This is a text 'single' and "double" quote in it.

echo $"This is a text 'single' and \"double\" quote in it."
This is a text 'single' and "double" quote in it.

echo $'This is a text \'single\' and \"double\" quote in it.'
This is a text 'single' and "double" quote in it.
lw0v0wl
  • 664
  • 4
  • 12
0

I think the answers above cover what you want to do, but I am still a little confused by your requirement. If the piece of code that you want to add to the script is static (which it looks like it is), can you not write it to a file once and do:

cat common-code > test.sh

within your script?

jawsnnn
  • 314
  • 2
  • 11