[英]Bourne shell script that tests for a file and creates it if not found
需要腳本來測試文件是否存在,如果存在,則輸出“找到文件”,如果不存在,則輸出“找不到文件”,然后創建文件。 可以同時使用位置參數嗎? 謝謝!
如果找到文件,則回顯“找到文件”,否則回顯“未找到文件” &&觸摸文件fi
if [[ -e /path/to/file ]]; then
echo "File found!"
else
echo "File not found! Creating it"
touch /path/to/file
fi
在回答有關/bin/sh
問題時,您可以輕松地將以上內容修改為:
filenm=/path/to/file/to/check.txt
if [ -f "$filenm" ] ; then
printf "file exists\n"
else
printf "file does not exist -- creating\n"
touch "$filenm"
fi
您也可以用test -f "$filenm"
替換[ stuff ]
上方的single-bracket test
在test -f "$filenm"
引號和分號之間留一個空格(例如, if test -f "$filenm" ; then
)。使用復合命令完成相同的操作。(使用test
但您也可以用[ ]
代替:
test -f "$filenm" && printf "file exists" || { printf "file does not exist\n"; touch "$filenm"; }
測試並創建文件后,最好確認已創建文件:
test -f "$filenm" || touch "$filenm"
test -f "$filenm" || { printf "error, unable to create %s\n" "$filenm"; exit 1; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.