How to add newlines into variables in bash script

  • When I do

    str="Hello World\n===========\n"
    

    I get the \n printed out too. How can I have newlines then?

    While the answers here are great, in reality I think you'd be better off using an array for this sort of thing most of the time.

  • enzotib

    enzotib Correct answer

    9 years ago

    In bash you can use the syntax

    str=$'Hello World\n===========\n'
    

    Single quotes preceded by a $ is a new syntax that allows to insert escape sequences in strings.

    Also printf builtin allows to save the resulting output to a variable

    printf -v str 'Hello World\n===========\n'
    

    Both solutions do not require a subshell.

    If in the following you need to print the string, you should use double quotes, like in the following example:

    echo "$str"
    

    because when you print the string without quotes, newline are converted to spaces.

    What is the syntax `str=$'Hello World\n===========\n'` called? variable substitution?

    @zengr: It's called ANSI-C quoting, and it's also supported in `zsh` and `ksh`; however, it is NOT POSIX-compliant.

    @mkelement0, it comes from ksh93, is also supported by zsh, bash, mksh and FreeBSD sh, and its inclusion in the next major revision of POSIX is under discussion

    Doesn't seem to work with double quotes? e.g. `str=$"My $PET eats:\n$PET food"` ? This approach works for double quotes

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM