[英]Unix Shell Script to backup a file
我是Shell腳本的新手,我正在嘗試使用Shell腳本將文件“ main.sh”備份到“ main.sh.bak”。 如果文件存在,請執行復制,否則顯示一條消息。 下面是我正在嘗試的腳本,我需要在“如果”條件下提供幫助,以檢查文件在當前目錄中是否存在。
#!/bin/bash
echo "enter the file name"
read FILE
if [ -f $FILE ]; then
cp $FILE $FILE.bak
echo "file successfully backed up"
else
echo "file does not exists"
exit 1
fi
exit 0
現有常規文件的test
命令( [ xxx ]
與test xxx
相同)如下:
if [ -f $FILE ]; then
<do something>
else
<do something>
fi
重要說明: -f
用於常規文件 ,例如,不適用於符號鏈接或目錄。 因此,如果您的文件可以是普通文件以外的其他文件,請鍵入man test
以更多地了解所有test
選項並適應您的特定情況。
您可以檢查此句子是否存在文件:
if [ -e $ FILE ]
帶[ ]
Usign條件與命令test
相同,有更多選項可檢查文件,例如:
-b FILE
FILE exists and is block special
-d FILE
FILE exists and is a directory
-f FILE
FILE exists and is a regular file
還有更多,請執行man test
以查看所有選項
您的腳本中也有一個錯誤。 if
語句后缺少分號。
所以
if [ $FILE ] then
應該變成:
if [ $FILE ]; then
echo -n "enter file name : "
read file
if [ -e $path/main.sh ]; then
cp /path/main.sh /path/main.bak
echo "Successfully back up"
else
echo "failed"
fi
exit 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.