linuxbashshell

Formatting string with printf


Here's the script I am executing:

#!/bin/bash
...
function myprint() {
  cp=$1
  targetpermission=$2
  t1="RESOURCE"
  t2="Current Permission"
  t3="New Permission"
  printf "%s : %s ===> %s\n",$t1,$t2,$t3
}

myprint

Expected output:

RESOURCE : Current Permission ===> New Permission

Output I am getting:

    [abhyas_app01@localhost safeshell]$ ./test1.sh 
Permission,New : Permission ===> 
,RESOURCE,Current[abhyas_app01@localhost safeshell]$

Just what's going on? How do I get the expected output?

PS - echo is not an option, because eventually I am going to justify the strings using %-Ns where N is a calculated based on terminal width.


Solution

  • In the shell, printf is a command and command arguments are separated by spaces, not commas.

    Use:

    printf "%s : %s ===> %s\n" "$t1" "$t2" "$t3"
    

    The double quotes are necessary too; otherwise the Current Permission and New Permission arguments will be split up and you'll get two lines of output from your single printf command.

    I note that your function takes (at least) two arguments, but you do not show those being printed or otherwise used within the function. You may need to revisit that part of your logic.


    With your current logic:

    t1="RESOURCE"
    t2="Current Permission"
    t3="New Permission"
    printf "%s : %s ===> %s\n",$t1,$t2,$t3
    

    you really pass to printf:

    printf "%s : %s ===> %s\n,RESOURCE,Current" "Permission,New" "Permission"
    

    Note how the 'format string' argument includes all of $t1 and part of $t2. You only provide two arguments for the three %s formats, so the third one is left empty. The output is:

    Permission,New : Permission ===> 
    ,RESOURCE,Current
    

    with a space at the end of the first line and no newline at the end of the second 'line' (hence your prompt appears immediately after Current).