Is there another simple way to append line to end of file other than `>>`?
Set the shell's noclobber
option:
bash-3.2$ set -o noclobber
bash-3.2$ echo hello >foo
bash-3.2$ echo hello >foo
bash: foo: cannot overwrite existing file
bash-3.2$
If you are worried your file will be damaged by >
operator you can change your file attribute to append only:
In ext2/ext3/ext4 filesystem: chattr +a file.txt
In XFS filesystem: echo chattr +a | xfs_io file.txt
And if you want a function, I made a function for myself already (I used it in service file for logging outputs), You can change it for your purpose:
# This function redirect logs to file or terminal or both!
#@ USAGE: log option data
# To the file -f file
# To the terminal -t
function log(){
read -r data # Read data from pipe line
[[ -z ${indata} ]] && return 1 # Return 1 if data is null
# Log to /var/log/messages
logger -i -t SOFTWARE ${data}
# While loop for traveling on the arguments
while [[ ! -z "$*" ]]; do
case "$1" in
-t)
# Writting data to the terminal
printf "%s\n" "${data}"
;;
-f)
# Writting (appending) data to given log file address
fileadd=$2
printf "%s %s\n" "[$(date +"%D %T")] ${data}" >> ${fileadd}
;;
*)
;;
esac
shift # Shifting arguments
done
}
Use tee
with the append option:
foo | tee -a some-file
# or
tee -a some-file <<EOF
blah blah
EOF
# or
tee -a some-file <<<"blah blah"