Запись в файл

Файлы / Текстовые файлы

fileName="file.txt"

#> creates the file or empties an existing one;
#echo adds the line feed at the end
echo "Line 1" > "$fileName"

#a group { } sends the output of several commands into one file,
#and the file is opened once
{
    echo "Line 1"
    printf 'Line %d\n' 2
} > "$fileName"
size=$(stat -c %s "$fileName")
#size is 14: > emptied the file before writing

#trap: > deletes the old text silently; noclobber forbids it
set -o noclobber
echo "Line 3" 2> /dev/null > "$fileName" && written=true || written=false
#written is false
set +o noclobber

echo "size is $size"
echo "written is $written"
echo "text is:"
cat "$fileName"
rm "$fileName"