【问题标题】:Unix Shell Script to backup a file用于备份文件的 Unix Shell 脚本
【发布时间】:2015-12-04 07:41:17
【问题描述】:

我是 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

【问题讨论】:

标签: bash shell unix


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的建议。你能帮我一些文章/网站,我可以从中学习/获取 Shell 脚本的实际示例。显然,学习 shell 脚本并实现它是最重要的。因此,某些实际示例会很有用。
  • 我经常推荐这个 bash 初学者指南:tldp.org/LDP/Bash-Beginners-Guide/html/index.html。它可能不是最新的,但我发现它写得很好。
【解决方案2】:

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

if [ -e $ FILE ] 

[ ] 的签名条件与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查看所有选项

【讨论】:

    【解决方案3】:

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

    所以

    if [ $FILE ] then
    

    应该变成:

    if [ $FILE ]; then
    

    【讨论】:

      【解决方案4】:
      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;
      

      【讨论】:

      • 请为您的回答添加简短的解释,以供未来访问者参考。
      猜你喜欢
      • 2012-11-14
      • 2015-10-03
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      相关资源
      最近更新 更多