2014-12-19 78 views
0

我有一個文件的測試是在目錄中已經存在,當我使用如何在重定向文件時獲取提示信息?

`cat > test` or `ls > test` 

文件中的內容將被截斷,且數據會丟失,所以我重定向文件之前,想提示信息。你的幫助將是最有用的。

在此先感謝。

+1

FYI:'設置-C'(noclobber選項)會阻止您覆蓋文件是這樣的。你可以用'> |'覆蓋這個...... Re:提問,只需用'if [-f myfile]'用'read'得到答案...... – Carpetsmoker

+0

我創建了一個更完整的例子作爲答案... – Carpetsmoker

+0

@Carpetsmoker - 是它的工作,有沒有其他方式? 「集-C」的用途是什麼? –

回答

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"