当我使用
时,我有一个已存在于目录中的文件测试 `cat > test` or `ls > test`
文件中的内容将被截断,数据将丢失,所以我想在重定向文件之前提示一条提示信息。你的帮助最有用。
提前致谢。
答案 0 :(得分:0)
可能是一个例子:
#!/bin/sh
# Prevent > from overwriting files, use >| to overwrite files anyway
# It's good for safety to always enable this...
set -C
file=xxx
# Test if file exist with -f
if [ -f "$file" ]; then
echo "Overwrite $file? [Y/n]"
# Read user input
read answer
# Is the answer "n" or "N", we exit
# The default is to continue on any other input (you could change this, of course)
case "$answer" in
[nN]) exit 2 ;;
esac
fi
# Overwrite the file, we use >| because we set noclobber
echo 'New' >| "$file"