Home > database >  How do I escape an argument of a bash script in awk?
How do I escape an argument of a bash script in awk?

Time:01-09

I have the following issue. I want to run a script with 2 parameters like:

./Myscript.sh $1 $2

$1 is a number, nothing special but $2 It's actually a message that looks like this:

“My message`-12355, this is a message !56432-I am sure it`s a message-46583”. 

This message was actually extracted with an awk from some log files. Myscript.sh executes a curl http post and uses the $1 and $2 as parameters for creating the json in curl command like

-d '{"number":"$1","message":"$2"}'

My question is how do I “escape” the argument $2 since the message contains special characters?

Thanks

I'm calling Myscript.sh from another script in a awk command using:

system(./Myscript.sh “$1” \”$2\”)

I was thinking to use backslashes to “escape” but this not seems to work. Any ideas or help would be great. Thanks a lot!

CodePudding user response:

I suggest to use " and not .

system("./Myscript.sh \"" $1 "\" \"" $2 "\"")

CodePudding user response:

you have exclamation mark ("!") in your shell $2 - I'd safely single-quote them if I were you ::

 sh: ./Myscript.sh: No such file or directory

 system() command :::

      './Myscript.sh' '1114111' 
                      'My message`-12355, this is a 
                          message !56432-I'\''m sure it`s a message-46583'

# gawk profile, created Mon Jan  9 05:37:09 2023
# Rule(s)

 1 ' {
 1      print "system() command :::\f\f\r\t",

               system_cmd = escSQ($1)  (_ = " ") 
                            escSQ($2)_ escSQ($3)
 1      system(system_cmd)
    }

 3  function escSQ(__,_) {

 3         _ = "\47"
 3      gsub(_,"&\\" (_)_,__)

 3      return (_)(__)_
    }'

ps : this approach is okay only if none of the command items have items that need to be interpreted by the shell, e.g. ~ (as prefix for script itself) or $? etc

  • Related