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 ctopkaya@ ls /opt/cinar/packages/libcnrhttp2_* -lr | awk 'NR==1'

enter image description here

declare -r libcnrhttp2="libcnrhttp2_"
declare -r root="/opt/cinar/packages"
declare -r destination="/opt/cinar/packages"
declare -r id=ctopkaya
declare -r host=
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 "--------------"
  • 3
    Please copy and paste text from your terminal rather than posting screenshots. – user413007 Jul 22 '20 at 8: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 8:20
  • You actually answered this one at unix.stackexchange.com/a/397444/5132 a while back, Kusalananda. (-: – JdeBP Jul 22 '20 at 9: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 9: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 </dev/null within loops too (belt and braces philosophy). – Paul_Pedant Jul 23 '20 at 10:01

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.