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
Unix Shell Script to backup a file
提问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 test
command ([ 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: -f
is for regular files, that is, for instance, not symbolic links or directories. So, if your filescan be something else than regular files, type man test
to know more about all test
options 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 test
there 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 test
to see all options
还有更多,请执行man test
以查看所有选项
回答by FrW
There is also an error in your script. You are missing an semicolon after the if
statement.
您的脚本中也有错误。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;