Bash – Write Text File

Background

Writing simple text files in Bash.

Code

Script


#!/bin/bash

function dataGenerate(){

    declare n_=$1
    declare -n aData_=$2

    declare i_=0
    declare dta_=0

    #Iterate
    while [ $i_ -lt $n_ ]
    do

	#Randomly Generate number    
        dta_=$[RANDOM]

	#Set array data
	aData_[i_]=$dta_    

	#Increment Pointer
	i_=$[$i_+1]


    done	    

}

function dataDisplay(){

    declare -n aData_=$1

    declare i_=0;
    declare n_=0;
    declare dta_=0;

    #get size of the array
    n_="${#aData_[@]}"

    #iterate array
    while [ $i_ -lt $n_ ]
    do

       dta_=${aData_[$i_]}

       echo "$i_) $dta_"

       i_=$[$i_+1]

    done



}

function dataWrite()
{


    declare i_=0;
    declare n_=0;
    declare dta=0;

    declare filename_=$1
    declare -n aData_=$2

    #get array size   
    n_="${#aData_[@]}"

    #truncate file
    `cp /dev/null $filename_`

    #iterate array
    while [ $i_ -lt $n_ ]
    do

       dta_=${aData_[$i_]}

       #write line
       echo "$dta_" >> $filename_

       i_=$[$i_+1]

    done

}

numberofElements=10
filename="datafile.txt"

dataGenerate $numberofElements arrayData

#comment out display to terminal for now
#dataDisplay arrayData

dataWrite   $filename arrayData 

 

Display File

Cat

Syntax


cat [filename]

Sample


cat datafile.txt

Output

Output – Image

Output – Text


>cat datafile.txt 
16520
18162
26381
6103
23043
5773
8748
2123
3781
22550

Source Code Control

GitHub

Gist

Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s