Printf example in bash does not create a newline

前端 未结 8 1737
臣服心动
臣服心动 2020-12-09 08:20

Working with printf in a bash script, adding no spaces after \"\\n\" does not create a newline, whereas adding a space creates a newline, e. g.:

8条回答
  •  没有蜡笔的小新
    2020-12-09 08:29

    Maybe people will come here with the same problem I had: echoing \n inside a code wrapped in backsticks. A little tip:

    printf "astring\n"
    # and 
    printf "%s\n" "astring" 
    # both have the same effect.
    # So... I prefer the less typing one
    

    The short answer is:

    # Escape \n correctly !
    
    # Using just: printf "$myvar\n" causes this effect inside the backsticks:
    printf "banana
    "
    
    # So... you must try \\n  that will give you the desired 
    printf "banana\n"
    
    # Or even \\\\n if this string is being send to another place 
    # before echoing,
    
    buffer="${buffer}\\\\n printf \"$othervar\\\\n\""
    

    One common problem is that if you do inside the code:

    echo 'Tomato is nice'
    

    when surrounded with backsticks will produce the error

    command Tomato not found.
    

    The workaround is to add another echo -e or printf

    printed=0
    
    function mecho(){
      #First time you need an "echo" in order bash relaxes.
      if [[ $printed == 0 ]]; then
        printf "echo -e $1\\\\n"
        printed=1
      else
        echo -e "\r\n\r$1\\\\n"
      fi
    }
    

    Now you can debug your code doing in prompt just:

    (prompt)$  `mySuperFunction "arg1" "etc"`
    

    The output will be nicely

     mydebug: a value
     otherdebug: whathever appended using myecho
     a third string
    

    and debuging internally with

    mecho "a string to be hacktyped"
    

提交回复
热议问题