我正在使用 simple 写入文件echo
(我愿意使用其他方法)。
写入已存在的文件时,我可以让 echo 提示用户是否覆盖吗?
例如,也许像-i
这样的论点会起作用?
echo -i "new text" > existing_file.txt
Run Code Online (Sandbox Code Playgroud)
期望的结果是提示用户是否覆盖...
echo -i "new text" > existing_file.txt
Do you wish to overwrite 'existing_file.txt'? y or n:
Run Code Online (Sandbox Code Playgroud)
重定向>
是由 shell 完成的,而不是由echo
. 事实上,shell 在命令启动之前就进行了重定向,并且默认情况下 shell 将覆盖任何具有该名称的文件(如果存在)。
如果存在任何文件,可以使用 shell 选项来防止 shell 覆盖noclobber
:
set -o noclobber
Run Code Online (Sandbox Code Playgroud)
例子:
$ echo "new text" > existing_file.txt
$ set -o noclobber
$ echo "another text" > existing_file.txt
bash: existing_file.txt: cannot overwrite existing file
Run Code Online (Sandbox Code Playgroud)
要取消设置该选项:
set +o noclobber
Run Code Online (Sandbox Code Playgroud)
如果不手动执行一些操作(例如定义函数并每次使用它),您将无法获得任何选项,例如接受用户输入来覆盖任何现有文件。
使用test
命令(由方括号别名[
)查看文件是否存在
$ if [ -w testfile ]; then
> echo " Overwrite ? y/n "
> read ANSWER
> case $ANSWER in
> [yY]) echo "new text" > testfile ;;
> [nN]) echo "appending" >> testfile ;;
> esac
> fi
Overwrite ? y/n
y
$ cat testfile
new text
Run Code Online (Sandbox Code Playgroud)
或者把它变成一个脚本:
$> ./confirm_overwrite.sh "testfile" "some string"
File exists. Overwrite? y/n
y
$> ./confirm_overwrite.sh "testfile" "some string"
File exists. Overwrite? y/n
n
OK, I won't touch the file
$> rm testfile
$> ./confirm_overwrite.sh "testfile" "some string"
$> cat testfile
some string
$> cat confirm_overwrite.sh
if [ -w "$1" ]; then
# File exists and write permission granted to user
# show prompt
echo "File exists. Overwrite? y/n"
read ANSWER
case $ANSWER in
[yY] ) echo "$2" > testfile ;;
[nN] ) echo "OK, I won't touch the file" ;;
esac
else
# file doesn't exist or no write permission granted
# will fail if no permission to write granted
echo "$2" > "$1"
fi
Run Code Online (Sandbox Code Playgroud)