bash 用于备份文件的 Unix Shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34083235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:59:49  来源:igfitidea点击:

Unix Shell Script to backup a file

bashshellunix

提问by B Ashwin

i am new to shell scripting, i am trying to backup a file "main.sh" to "main.sh.bak" using a shell script. If the file exists perform the copy, else display a message. below is the script i am trying, i need to help in the "if" condition to check if the file exists or not in the current directory.

我是 shell 脚本的新手,我正在尝试使用 shell 脚本将文件“main.sh”备份到“main.sh.bak”。如果文件存在则执行复制,否则显示一条消息。下面是我正在尝试的脚本,我需要在“if”条件下帮助检查文件是否存在于当前目录中。

#!/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

回答by Renaud Pacalet

The testcommand ([ xxx ]is the same as test xxx) for an existing regular file looks like:

现有常规文件的test命令([ xxx ]与 相同test xxx)如下所示:

if [ -f $FILE ]; then
  <do something>
else
  <do something>
fi

Important note: -fis for regular files, that is, for instance, not symbolic links or directories. So, if your filescan be something else than regular files, type man testto know more about all testoptions and adapt to your specific case.

重要说明:-f适用于常规文件,例如,不是符号链接或目录。因此,如果您的文件不是常规文件,请键入man test以了解有关所有test选项的更多信息并适应您的特定情况。

回答by Joan Esteban

You can check if is a file exists with this sentence:

你可以用这句话检查文件是否存在:

if [ -e $ FILE ] 

Usign condition with [ ]are the same than command testthere are more options to checks files, for instance:

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

And much more, please execute man testto see all options

还有更多,请执行man test以查看所有选项

回答by FrW

There is also an error in your script. You are missing an semicolon after the ifstatement.

您的脚本中也有错误。if语句后缺少分号。

So

所以

if [ $FILE ] then

Should become:

应该变成:

if [ $FILE ]; then

回答by sid

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;