NASutils Knowledge BaseUnofficialPolski

Bash · lesson 19 of 30 · Files and errors · bonusWrite and read a file

Write with printf and >, add with >> and read with while. cp, mv and rm do the rest.

Programming on the NAS › Bash in 30 lessons

19-files.sh Download 19-files.sh

#!/usr/app/TurboShell/bin/bash
# > makes a new file, >> adds to its end
printf '%s\n' "two disks" "a network cable" >shopping.txt
echo "a UPS" >>shopping.txt

n=0
while IFS= read -r line; do
  n=$((n + 1))
  echo "$n. $line"
done <shopping.txt

cp shopping.txt copy.txt
mv copy.txt old-list.txt
rm old-list.txt
echo "$(wc -l <shopping.txt) lines in shopping.txt"

Terminal

$ bash 19-files.sh
1. two disks
2. a network cable
3. a UPS
3 lines in shopping.txt
$ cat shopping.txt
two disks
a network cable
a UPS

Exercise

Write ten numbers into a file and read back their sum.