Reading and writing files

Read project files line by line, redirect output with > and >>, write here-documents, and keep temporary files under /tmp.

Runs in Zerethon IDE · Bash 5.2 Official Bash documentation ↗

A run sees the project's files in its working folder, read-only. A script may write files under /tmp; they are deleted when the run ends.

main.sh
tail -n +2 data.csv | while IFS=, read -r name score; do
  echo "$name scored $score"
done

count=$(( $(wc -l < data.csv) - 1 ))
echo "count=$count" > /tmp/report.txt
echo "written by main.sh" >> /tmp/report.txt
cat /tmp/report.txt

cat > /tmp/note.txt <<EOF
Rows: $count
EOF
cat /tmp/note.txt
data.csv
name,score
ada,90
alan,85

Output

ada scored 90
alan scored 85
count=2
written by main.sh
Rows: 2
  • > replaces a file, >> appends to it, < reads a file as input, 2> redirects errors.
  • A <<EOF here-document writes several lines; variables inside it are expanded unless you write <<'EOF'.
  • Variables set inside cmd | while ... are lost after the loop (the loop runs in a subshell); use while ...; done < file when you need them afterwards.
  • Writing next to your script (> out.txt) fails with Read-only file system — use /tmp/out.txt or mktemp.