2

I've been trying to create a Bash shell script that would create and alter a file called list. Effectively, my goal with the program is to append names to a list, creating the file with a header (if necessary).

However, the script currently fails at one particular point: Whenever I run the script again, the old name disappears and is replaced by the name that was just entered. How can I solve this?

My script:

#!/bin/bash
#Please sign your name here.

echo "Hi, what's your name?"
read name
echo "Hi $name, welcome to the Linux course!"

echo Course Attendees > list
echo $name >> list

Example of problem:

$ bash list.sh
Hi, what's your name?
Test
Hi Test, welcome to the Linux course!

$ cat list
Course Attendees
Test

$ bash list.sh
Hi, what's your name?
Test2
Hi Test, welcome to the Linux course!

$ cat list
Course Attendees
Test2
Eliah Kagan
  • 119,640

1 Answers1

4

In Bash, there are two ways of writing to a file (technically, there are a lot more, but for all intents and purposes for this answer, there are two):

First off is the > operator, as you're using in this line:

echo Course Attendees > list

The > operator will overwrite anything existing in the file with the new contents of the file. In effect, it deletes the file, and creates a new one with the same name.

Secondly is the >> operator, as used here:

echo $name >> list

This will append lines to an existing file, or create a new one if it doesn't exist.

When you run your script, you're always overwriting your course list with the "Course Attendees" header, causing this error. Alter your program to only append lines if the "Course Attendees" header is present. My personal suggestion would be to check if the file exists. If it does, use only the append operation. Otherwise, give it the header and create it.

Or, more elegantly, only run echo Course Attendees > list if the file does not exist. See this SO answer for more info as to how to run a check like this.

Kaz Wolfe
  • 34,680