1

I'm newbie in bash scripting

I want to format command with printf to prepare execution and assign into variable.

But it is executing immediately. It is listing /opt/cinar/packages/libcnrhttp2_* instead of writing it as string into command string.

I was expecting this:

ssh [email protected] ls /opt/cinar/packages/libcnrhttp2_* -lr | awk 'NR==1'

enter image description here

#!/bin/bash
declare -r libcnrhttp2="libcnrhttp2_"
declare -r root="/opt/cinar/packages"
declare -r destination="/opt/cinar/packages"
declare -r id=ctopkaya
declare -r host=192.168.13.137
declare -r remote=$id"@"$host

declare cmd=""
printf -v cmd ssh %s ls %s/%s* -lr | awk 'NR==1' $remote /opt/cinar/packages libcnrhttp2_

cd $destination
echo "--------------"
echo $cmd
echo "--------------"
uzay95
  • 111
  • 4
  • 3
    Please copy and paste text from your terminal rather than posting screenshots. –  Jul 22 '20 at 08:02
  • It's unclear what you want to happen. You print the string saved in `$cmd` by `printf -v cmd` using `echo $cmd`. This is why that string is outputted. The generated command in `$cmd` is not executed by the script that you show. – Kusalananda Jul 22 '20 at 08:20
  • You actually answered this one at https://unix.stackexchange.com/a/397444/5132 a while back, Kusalananda. (-: – JdeBP Jul 22 '20 at 09:10
  • There are other issues. The `-lr` options to `ls` must be before the filenames. The `awk` will only show a single line from the pipe, not the first line of each item in the `ls` command. – Paul_Pedant Jul 22 '20 at 09:14
  • Another general issue. ssh has a nasty habit of assuming the remote command will read the local stdin, so it reads-ahead (the first 2048 bytes, IIRC) and sends that over with the command. If the ssh is within a script loop (e.g. a list of hosts), the first ssh consumes a chunk of that list. See man ssh, the -f and -n options. Personally, I also explicitly redirect ssh – Paul_Pedant Jul 23 '20 at 10:01

1 Answers1

1

The command which is supposed to format the text is within double quotes and is thus treated as text to print. To print the result of a command instead put it inside $() (command substitution), like:

printf "$(printf foo | awk 'NR==1') bar"
DisplayName
  • 11,468
  • 20
  • 73
  • 115