-1

I need to run the following command in a bash script.

The command needs to be run inside a GNU screen so I can see the progress. So the command needs to be in quotes, but because of that I am having problems with the syntax and the code isn't running properly.

I have a file in a remote server called textfile.txt. It looks like this.

The command gawk command runs fine on its own.

test-server-name 1
test-server-name 2
test-server-name 3
...
test-server-name 23
test-server-name 24
...

I run a screen command together with an ssh command that runs a gawk command to modify a line in the text file, in this case, it should look for test-server-name-1 and add a 0 next to it like this.

test-server-name 1 0
test-server-name 2
test-server-name 3
...
test-server-name 23
test-server-name 24
...

This is what my script looks like in my local server.

localhostname='test-server-name-1'
counter=1
function='textfile'

screen -dmS $counter "ssh -i ~/.ssh/ssh-key username@masteripaddress 'gawk -i inplace -v n='0' -v s='${localhostname}-${function}' '$1 == s { $2 = n } 1' /home/master/Documents/${function}.txt';exec bash;"

But when I run it, the script runs, and I get this error in the attached screen,

gawk: cmd. line:1: ==
gawk: cmd. line:1: ^ syntax error

How do I fix it? What characters need to be escaped

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
anarchy
  • 3,709
  • 2
  • 16
  • 48
  • 1
    You have nested single quotes – anubhava Sep 15 '20 at 17:22
  • is there a way to fix this ? im getting confused with the syntax as well – anarchy Sep 15 '20 at 17:23
  • 1
    try: `screen -dmS $counter "ssh -i ~/.ssh/ssh-key username@masteripaddress \"gawk -i inplace -v n='0' -v s=$localhostname '$1 == s { $2 = n } 1' /home/master/Documents/${function}.txt\";exec bash;"` – anubhava Sep 15 '20 at 17:24
  • hey man I m getting the same error, I modified the code a bit please take another look, the s= command needs to be in quotes I think – anarchy Sep 15 '20 at 17:32
  • 1
    shell, screen, ssh, gawk -- you need to handle nested quotation for all of them. dont do this. put a shell script on remote side and call it via ssh. – pynexj Sep 16 '20 at 01:36
  • 1
    why `exec bash` in the end? – pynexj Sep 16 '20 at 01:38

1 Answers1

1

(Don't do this. It'll be much easier if you put a script on remote side.)

Just give you an example (with \-style escaping):

[STEP 101] $ # to run an awk command locally
[STEP 102] $ title='THE SUM: '
[STEP 103] $ printf '%d\n' {1..10} | awk -v title="$title" '{ sum += $1 } END { print title sum }'
THE SUM: 55
[STEP 104] $
[STEP 105] $ # to run the awk command thru screen + ssh
[STEP 106] $ # added 'sleep 1' for easy watching
[STEP 107] $ title='THE SUM: '
[STEP 108] $ screen -c /dev/null -m ssh 127.0.0.1 printf\ \'%d\\n\'\ \{1..10\}\ \|\ awk\ -v\ title=\'"$title"\'\ \'\{\ sum\ +=\ \$1\ \}\ END\ \{\ print\ title\ sum\ \}\'\;\ sleep\ 1
THE SUM: 55
[screen is terminating]
[STEP 109] $
pynexj
  • 19,215
  • 5
  • 38
  • 56