date command not found in shell script

Viewed 10610

my shell script backup.sh as below, when i execute this script, i got the error "date: command not found". I have checked that there are no space between = and the parameters. Could anydody give an explain about this error. Thanks.

x00004:/home/ # cat backup.sh 
#!/bin/sh
set +x

source ./conf.sh

if [ $# != 2 ] ; then
    echo " Usage: $0 [sftp user] [sftp pwd]"
    exit 1;
fi

DATE=`date +%y-%m-%d--%H:%M:%S`
echo "${DATE}"
file=test.tar.gz
echo "Starting to backup files..."

#to backup files to sftp server

x00004:/home/ # ./backup.sh usr pwd
./backup.sh: line 11: date: command not found

Starting to backup files...
x00004:/home/poc/src # 
2 Answers

Shells can't find commands if the commands aren't in directories in $PATH. Quick fix: replace date with /bin/date. However, a similar problem might occur in conf.sh or backup.sh, so a more global solution is to echo "$PATH" at the beginning of your script, figure out what's missing, and and fix it, e.g., PATH=/bin:$PATH.

Best way is to use the bash/shell command called command -v to dynamically check where is your date path.

DATE_BIN=$(command -v date)
DATE=`${DATE_BIN} +%y-%m-%d--%H:%M:%S`
Related