Mahmoud Emam
Mahmoud Emam

Reputation: 1527

Command aliases in my script

I am creating a script for copying files or directory with a date attached to its name, for example if the file name is test it will be test-20130901.bkup

and this is my script

#!/usr/bin/bash
set -x

getopts fd TYPE
[ $TYPE = "d" ] && alias cp="cp -r"

backup_error() {
        echo "${0##*/}: $1"
        exit -1
}

typeset -r FROM_DIR=$2 TO_DIR=$3
if [ ! -e $FROM_DIR -a ! -d $FROM_DIR ] || [ ! -e $TO_DIR -a ! -d $TO_DIR ]
then
        backup_error "One of the directories isn't exist or it maybe a file";
fi

typeset -r DATE=$(date "+%Y%m%d")
for filename in $FROM_DIR/*
do
        if [ -$TYPE $filename ]
        then
                cp $filename $TO_DIR/${filename##*/}-$DATE.bkup
        fi
done

unalias cp

In the script I check if the user wants to run the script on files only or on directories only. -f for files only -d for directories only

[ $TYPE = "d" ] && alias cp="cp -r", this line to check if the script runs for directory I must use cp -r so I make an alias for cp to be cp -r

but when I use set -x to debug I find the when a user use -d option the cp command in the if still the original one not the alias.

Debugging:

> ./backup.sh -d . .
+ getopts fdb TYPE
+ '[' d = d ']'
+ alias 'cp=cp -r'
+ typeset -r FROM_DIR=. TO_DIR=.
+ '[' '!' -e . -a '!' -d . ']'
+ '[' '!' -e . -a '!' -d . ']'
++ date +%Y%m%d
+ typeset -r DATE=20130901
+ '[' -d ./backup.sh ']'
+ '[' -d ./dir1 ']'
+ cp ./dir1 ./dir1-20130901.bkup
cp: ./dir1: is a directory
+ '[' -d ./file1 ']'
+ '[' -d ./file2 ']'
+ '[' -d ./test.sh ']'
+ unalias cp

Upvotes: 2

Views: 235

Answers (1)

konsolebox
konsolebox

Reputation: 75458

Use a function instead:

if [[ $TYPE == d ]]; then
    function cp {
        command cp -r "$@"
    }
fi

And when in Bash, [[ ]] is recommended over test or [ ].

Also quote please quote your variables properly between "" to prevent word splitting and unexpected pathname expansion.

Other caveats:

    exit -1  ## exit can only accept 8-bit integral values from 0 to 255. -1 here is orthodox and is equivalent to 255.

You should quote the variables here or use [[ ]]:

    if [[ ! -e $FROM_DIR && ! -d $FROM_DIR ]] || [[ ! -e $TO_DIR && ! -d $TO_DIR ]]

    if [ "-$TYPE" "$filename" ]  ## for custom operators, test is better: test "-$TYPE" "$filename"

            cp "$filename" "$TO_DIR/${filename##*/}-$DATE.bkup"

for filename in "$FROM_DIR"/*

Lastly make sure you run your script as:

bash script.sh -f from_dir to_dir
# Or
bash script.sh -d from_dir to_dir

Upvotes: 2

Related Questions