What should I do if print fails to interpret backslash and java exclamation mark?

443    Asked by LisaHenderson in Java , Asked on Oct 10, 2022

I am writing a java program from terminal using printf and redirecting its output to a .java file but printf fails to interpret the horizontal backslash tab (t), and when I have an exclamation mark (!) in the string, it doesn't even print and fails with this error:

bash: !": event not found

How do I force printf to include a horizontal tab?

And how do I include an exclamation without getting the above error?

commandline argument:
$ printf "%sn" "public class {" "tpublic static void main(String[] args) {" "dogBark()" "}" "public static void dogBark() {" "System.out.println("Woof")" "}" "}" > barkingDog.java
output from .java file
$ less barkingDog.java
public class {
public static void main(String[] args) {
dogBark()
}
public static void dogBark() {
System.out.println(Woof)
}
}
Answered by Logan Harris

I think you can accomplish what you want using ANSI-C quoting like so:


printf "%s
" "public class {"
$'public static void main(String[] args) {'
"dogBark()"
"}"
"public static void dogBark() {"
"System.out.println("Woof")"
"}"
"}" > barkingDog.java
Output:
public class {
        public static void main(String[] args) {
dogBark()
}
public static void dogBark() {
System.out.println(Woof)
}
}

As for the java exclamation mark, when history expansion is enabled bash will attempt to expand ! when inside double quotes. So single quote it or escape it with .



Your Answer

Interviews

Parent Categories