How to read and write from a file in a Linux bash shell script

I’m currently writing a complicated Linux bash shell script where I need to keep a counter in an external file, and to do so, I need to be able to write to a file and then read from that file.

In short, this is how I write my counter to that file:

# create a variable to represent the filename
COUNTER_FILE="counter.tmp"

# write to the file
echo "0" > $COUNTER_FILE

Later in the code I increment the counter and write it to the file like this:

((count++))
echo $count > $COUNTER_FILE

Finally, this is how I read the counter from the file:

count=`cat $COUNTER_FILE`

Related: Looping over lines in a file

In a related note, if you need to loop over the lines a file in a bash shell script, this for loop works very well:

local filecount=1
IFS=$'\n'
for i in `cat $FILES_FOUND`
do
    if [ $filecount -eq $fileNumber ]; then
        filename=`echo $i | cut -d: -f1`
        exploreFile2 $filename
    fi
    (( filecount++ ))
done

As you can see, I use another counter in this for loop. I also use the input field separator variable IFS to state that lines are separated by newline characters. You need to do this whenever the lines in the file you’re reading contain blank spaces, which mine do. (In this code, the variable FILES_FOUND contains a list of filenames which I found earlier in my script, and those filenames can contain spaces.)

The end

If you need to see how to read from a file and write to a file in a Linux bash shell script, I hope this has been helpful.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.