简体   繁体   English

BASH:在printf中格式化字符串

[英]BASH : formatting string in printf

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. PS- echo不是一种选择,因为最终我将使用%-Ns来证明字符串的%-Ns ,其中N是根据端子宽度计算的。

In the shell, printf is a command and command arguments are separated by spaces, not commas. 在shell中, printf是命令,命令参数用空格而不是逗号分隔。

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. 否则,“ Current Permission和“ New Permission参数将被拆分,并且您将从单个printf命令获得两行输出。

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

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

Note how the 'format string' argument includes all of $t1 and part of $t2 . 注意“格式字符串”参数如何包括所有的$t1和部分$t2 You only provide two arguments for the three %s formats, so the third one is left empty. 您只为这三种%s格式提供了两个参数,因此第三个保留为空。 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 ). 在第一行的末尾有一个空格,在第二个“行”的末尾没有换行符(因此您的提示会在Current之后立即显示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM