BenoitParis
BenoitParis

Reputation: 3184

Escaping special characters in bash

I have this command in a bash script:

sudo java -jar ./myjar.jar name_%1$tY%1$tm.csv ./sql/blablab.sql someArgument

or

sudo java -jar ./myjar.jar "name_%1$tY%1$tm.csv" ./sql/blablab.sql someArgument

Any of these two commands will yield these 3 arguments:

Arguments :   name_%1%1.csv  ./sql/blablab.sql  someArgument

As you can see, % and/or $ did not get escaped. I'm looking for a way to escape them.

Best regards

Upvotes: 0

Views: 1113

Answers (2)

Faiz
Faiz

Reputation: 16255

Try this:

sudo java -jar ./myjar.jar 'name_%1$tY%1$tm.csv' ./sql/blablab.sql someArgument

This is assuming that you want to all $ characters unescaped to java. There's other ways:

example_$notAVar$aVar    # yields example_
example_\$notAVar\$aVar  # yields example_$notAVar$aVar
aVar=42
example_$notAVar$aVar    # yields example_42
'example_$notAVar$aVar'  # yields example_$notAVar$aVar
"example_\$notAVar$aVar" # yields example_$notAVar42
example_\$notAVar$aVar   # yields example_$notAVar42
'example_$notAVar'$aVar  # yields example_$notAVar42

Upvotes: 2

Alberto Miranda
Alberto Miranda

Reputation: 372

In bash a non-quoted backslash \ is the escape character. It preserves the literal value of the next character that follows, with the exception of \n. You don't need to escape the % character but you do have to escape the $ or bash will consider it a variable and expand it.

In your case,

sudo java -jar ./myjar.jar name_%1\$tY%1\$tm.csv ./sql/blablab.sql someArgument

should work.

Upvotes: 4

Related Questions