Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Actually I want to create an array of dates and compare it to the today date if it match with the current date then execute test.sh file otherwise exit the loop in bash script. I did like this...

#!/bin/bash

cd /home/user1

current_date=$(date +%Y-%m-%d)

array=['2016-03-02','2016-03-010','2016-05-10']

for i in "${array[@]}"
do
if [ $now -eq $i ]; then
        echo "executing your bash script file"
    ./myscript.sh
fi
done

when i execute above script then it gives error like

./sample.sh: line 6: [: 2016-03-02: integer expression expected
share|improve this question

Try it this way:

current_date=$(date +%Y-%m-%d)

array=('2016-03-02' '2016-03-010' '2016-05-10')

for i in "${array[@]}" ; do

    if [ "$current_date" == "$i" ]
        then echo "executing your bash script file"
        #./myscript.sh
    fi

done

The mistakes:

  1. don't use square brackets to declare an array in a bash script - these brackets make commands (see 'if'-tests)
  2. array-elements in bash scripts are separated by whitespaces (no commas)
  3. if you want to compare strings, use double-quotes around the variables, which hold these strings
  4. do not use '-eq' as operator here (because it's an arithmetic-operator). Instead use '==' or '!=' (see here too: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html)
share|improve this answer
    
yes its done! thank you so much for your kind effort. – guest111 Mar 2 at 11:33

You don't need to pull bash or arrays for that. You can do:

#! /bin/sh -
if grep -qx "$(date +%Y-%m-%d)" << EOF
2016-03-02
2016-03-01
2016-05-10
EOF
then
   test.sh
fi

or:

#! /bin/sh -
dates="2016-03-02 2016-03-01 2016-05-10"
case " $dates " in
  *" $(date +%Y-%m-%d) "*)
     test.sh
esac

Or just:

#! /bin/sh -
case $(date +%Y-%m-%d) in
  2016-03-02|2016-03-01|2016-05-10) test.sh
esac

For searchable arrays, I'd rather use zsh than bash:

#! /bin/zsh -

dates=(2016-03-02 2016-03-01 2016-05-10)
if ((dates[(I)$(date +%Y-%m-%d)])) test.sh
share|improve this answer
    
thanks everyone !! – guest111 Mar 3 at 3:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.