Linux - Bash Redirect a String to a file

12,214

You need to wrap your variables in double quotes:

echo "$newexpr" > "$path/$file"

The quotes around $path/$file aren't actually necessary in this case but they do no harm.

More generally, you should also use $( ) rather than backticks:

newexpr=$(awk '/^Build Number/{$4=$4+1;}1' "$path/$file")

If you want to achieve the effect of changing the file "in-place", you don't need to use a variable. You can use a temporary file like this:

awk '/^Build Number/{$4=$4+1;}1' "$path/$file" > /tmp/file && mv /tmp/file "$path/$file"

The importance of using quotes

The double quotes preserve the original format of the data. See this simple example, which uses set -x to activate debug mode. The commands that are being executed by the shell are shown on the lines beginning with +. Actually I see that you're already using #!/bin/bash -x. set -x does the same thing as that.:

$ s="1
> 2"
$ set -x
$ echo $s
+ echo 1 2
1 2
$ echo "$s"
+ echo '1
2'
1
2

The original string contains a newline but when you echo it without quotes, it is interpreted as two arguments to echo, instead of one argument that contains a newline. This is called field splitting. You can learn more about the importance of using double quotes by reading this this wiki article.

Share:
12,214
Alex Brodov
Author by

Alex Brodov

Updated on July 24, 2022

Comments

  • Alex Brodov
    Alex Brodov almost 2 years

    I wrote a simple script that is reading the file content and incrementing a a number inside this file, then i'm holding the change using awk, when i'm trying ro redirect the new String using '>' the whole string is redirected in one line and not like the original was which is 4 lines.

    #!/bin/bash -x
    
    # This script is for Incrementing build numbers
    
    path=/home/RND/abrodov
    file=tst.txt
    tst=`cat $path/$file`
    printf "this is the content of the file before incrementing: \n $tst"
    newexpr=`awk '/^Build Number/{$4=$4+1;}1' /home/RND/abrodov/tst.txt`
    printf "\n the new content \n $newexpr"
    echo $newexpr > $path/$file
    

    This is the original file before running the script:

    Major Release Number = 4
    Minor Release Number = 1
    Service Pack Release Number = 2
    Build Number = 22
    

    This is the content after i used the script:

    Major Release Number = 4 Minor Release Number = 1 Service Pack Release Number = 2 Build Number = 23
    

    I'm trying to figure out how can i redirect the text in the original format which is 4 lines.