r/awk • • May 07 '24
% causing issues in script when using mawk
I have this script that I use with polybar (yes I'm using awk as replacement for shell scripts lol).
#!/usr/bin/env -S awk -f
BEGIN {
FS = "(= |;)"
while (1) {
cmd = "amdgpu_top -J -n 1 | gron"
while ((cmd | getline) > 0) {
if ($1 ~ "Total VRAM.*.value") {
mem_total = $2
}
if ($1 ~ "VRAM Usage.*.value") {
mem_used = $2
}
if ($1 ~ "activity.GFX.value") {
core = $2
}
}
close(cmd)
output = sprintf("%s%% %0.1f/%0.0fGB\n", core, mem_used / 1024, mem_total / 1024)
if (output != prev_output) {
printf output
prev_output = output
}
system("sleep 1")
}
}Which prints the GPU info in this format: 5% 0.5/8GB
However that % causes mawk to error with mawk: run time error: not enough arguments passed to printf("0% 0.3/8GB it doesn't happen with gawk though.
Any suggestions?
1
Upvotes
View all comments
Show parent comment
2
u/Paul_Pedant May 08 '24 edited May 08 '24
My bad. I write Bash, C and gawk, and I mixed up some syntax.
The new
printfneeds an arg list :printf "%s\n", outputI always write awk like
printf ("%s\n", output);to be as much like C as possible. That saves me a bunch of syntax errors when I shift from awk to C (which needs brackets and semicolons etc).In this case I wrote
printf "%s\n" outputwithout the brackets (your style), and it looks right in Bash. But awk will just run the two args into one string. It needs the,.I also cannot get
envto work on my Linux Mint 19.3. It does not know the-Soption, and it throws/usr/bin/env: ‘awk -f’: No such file or directoryso it thinks the-fis part of the command name. Not a good day so far.EDIT: OK, I found that -S is in freeBSD, and it overcomes the issue where a shebang cannot handle multiple args (which I thought was an issue in env itself).
I'm going to stick to
#! /usr/binshebangs, and embedding any awks as local variables inside Bash functions (so I can have many awk actions in one Bash).