Shell Script backup a file HELP

Discussion in 'Programming/Scripts' started by anything, Feb 2, 2008.

  1. anything

    anything New Member

    could you please find a solution for this

    script that backup a file. The file name to backup should be provided as input parameter, the backup file should have the same file name with the extension ".bak". If the user provides no input parameter, the script should display an error message. If there is an input file name, but it does not exist, the script should display an error message. If the input file exists, the script should create the backup file and overwrite any existing backup file with the same name.
     
  2. topdog

    topdog New Member HowtoForge Supporter

    Code:
    #!/bin/bash
    #
    # Andrew <[email protected]>
    # Quick dirty script to backup a file
    # 03-02-2008
    #
    
    if [[ "$1" = "" || "$1" = "--help" ]]; then
            echo " Usage: $0 <file to backup>"
            echo ""
            exit 1
    fi
    
    if [ ! -r $1 ]; then
            echo "The file $1 does not exist"
            echo ""
            exit 1
    fi
    #work around for systems with cp -i alias
    aliased=0
    j=$(alias | grep cp &>/dev/null)
    if [ "$?" = "0" ]; then
            i=$(alias cp | grep '\-i' &>/dev/null)
            if [ "$?" = "0" ]; then
                    aliased=1
                    unalias cp
            fi
    fi
    # actual copy
    cp -a $1 $1.bak
    if [ $aliased = "1" ]; then
            alias cp='cp -i'
    fi
    
     
  3. anything

    anything New Member

    thank you, but can you add a massage inform that the backup is successfully created, when it do. and please could you give me a little explanation of it, I am really beginner on it. I need to understand the code.

    thanks
     
  4. topdog

    topdog New Member HowtoForge Supporter

    Comments are inline
    Code:
    #!/bin/bash
    #
    # Andrew <[email protected]>
    # Quick dirty script to backup a file
    # 03-02-2008
    #
    
    #check if any option was passed or --help
    if [[ "$1" = "" || "$1" = "--help" ]]; then
            echo " Usage: $0 <file to backup>"
            echo ""
            exit 1
    fi
    
    #check if file exists
    if [ ! -r $1 ]; then
            echo "The file $1 does not exist"
            echo ""
            exit 1
    fi
    #work around for systems with cp -i alias
    aliased=0
    j=$(alias | grep cp &>/dev/null)
    if [ "$?" = "0" ]; then
            i=$(alias cp | grep '\-i' &>/dev/null)
            if [ "$?" = "0" ]; then
                    aliased=1
                    unalias cp
            fi
    fi
    # actual copy
    cp -a $1 $1.bak
    if [ "$?" = "0" ]; then
            echo "The file $1 has been backed up !"
    fi
    
    #set alias back
    if [ $aliased = "1" ]; then
            alias cp='cp -i'
    fi
    
     
  5. anything

    anything New Member

Share This Page