2

I have a script that sends me some info about different machines, and it's working fine in Fedora machines, but Ubuntu 20.04 gives me error for only one printf. I can't seem to see what am I doing wrong. So the statement is:

#printf "Last logins (last -10) \n `last -10` \n"
Last logins (last -10) 
bash: printf: ` ': invalid format character
 vecn1    pts/8        tmux(1233684).

whereas similar statements works fine:

printf "Default gw (ip ro ls) \n`ip ro ls` \n"
Default gw (ip ro ls) 
default via 192.168.111.1 dev en0 proto dhcp src 192.168.111.6 metric 100 
192.168.111.0/24 dev en0 proto kernel scope link src 192.168.111.6 
192.168.111.1 dev en0 proto dhcp scope link src 192.168.111.6 metric 100 

What am I doing wrong? Maybe those "%" numbers? Not sure why are there. Normally is just a hostname (ip). If I do just last -10 following is the output

vecn1    pts/8        tmux(1233684).%3 Mon Dec 26 11:29 - 12:01  (00:31)
vecn1    pts/7        tmux(1233684).%2 Mon Dec 26 11:29 - 12:01  (00:31)
vecn1    pts/6        tmux(1233684).%1 Mon Dec 26 11:29 - 12:01  (00:31)
vecn1    pts/5        tmux(1233684).%0 Mon Dec 26 11:29 - 11:29  (00:00)
vecn1    pts/8        tmux(1232989).%3 Mon Dec 26 11:27 - 11:29  (00:01)
vecn1    pts/7        tmux(1232989).%2 Mon Dec 26 11:27 - 11:29  (00:01)
vecn1    pts/6        tmux(1232989).%1 Mon Dec 26 11:27 - 11:29  (00:01)
vecn1    pts/5        tmux(1232989).%0 Mon Dec 26 11:27 - 11:27  (00:00)
vecn1    pts/8        tmux(1198190).%3 Mon Dec 26 11:03 - 11:04  (00:00)
vecn1    pts/7        tmux(1198190).%2 Mon Dec 26 11:03 - 11:04  (00:00)

wtmp begins Wed Jun 22 17:27:34 2022

Thanks

muru
  • 193,181
  • 53
  • 473
  • 722
DenisZ
  • 123
  • 9

1 Answers1

2

Yes it's likely the % symbols.

You should always avoid injecting code into the format string of the printf function; instead pass the result of the command as a argument using the appropriate format specifier (%s in the case of a string):

printf 'Last logins (last -10)\n%s\n' "`last -10`"

or better (avoiding the deprecated backtick form of command substitution)

printf 'Last logins (last -10)\n%s\n' "$(last -10)"
steeldriver
  • 131,985
  • 21
  • 239
  • 326
  • Yep that works, Thanks. I'm not sure if I understand how exactly this (%s) works, as I've read printf manual, but didn't really get it. I also need to eliminate backticks from my scripts, you are right. – DenisZ Dec 26 '22 at 17:50
  • btw, how would I go about injecting code 2 times like: `printf "Uptime $(uptime) \nVersion $(uname -a) \n"` – DenisZ Dec 26 '22 at 17:59
  • @DenisZ ou can pass as many arguments as there are format specifiers - so `printf 'Uptime %s\nVersion %s\n' "$(uptime)" "$(uname -a)"` – steeldriver Dec 26 '22 at 18:01
  • I see, wonderful, that seems easy. – DenisZ Dec 26 '22 at 18:20