Zen*_*Zen 22 command-line shell bash io-redirection
最近我正在将短句回显到tree_hole
文件中。
我是echo 'something' >> tree_hole
用来做这项工作的。
但是我总是担心如果我输入错误>
而不是>>
,因为我经常这样做。
所以我在 bashrc 中创建了一个我自己的全局 bash 函数:
function th { echo "$1" >> /Users/zen1/zen/pythonstudy/tree_hole; }
export -f th
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有另一种简单的方法可以将行附加到文件的末尾。因为我可能需要在其他场合经常使用它。
有没有?
Cel*_*ada 47
设置 shell 的noclobber
选项:
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$
Run Code Online (Sandbox Code Playgroud)
如果您担心>
操作员会损坏您的文件,您可以将文件属性更改为仅附加:
在ext2/ext3/ext4文件系统中:chattr +a file.txt
在XFS文件系统中:echo chattr +a | xfs_io file.txt
如果你想要一个函数,我已经为自己做了一个函数(我在服务文件中使用它来记录输出),你可以根据你的目的更改它:
# 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
}
Run Code Online (Sandbox Code Playgroud)