bash - how to pass arg values to shell script within in a cronjob
I have cron entry that looks like this which works: (passing开发者_JAVA技巧 in 5 inputs)
30 10 * * 5 sh /home/test.sh hostnm101.abc /mypath/dir test foobar F008AR >> /logs/mytst.log 2>&1
I want to change it so I store inputs (4,5) foobar
and F008AR
in a separate file and read in by
script test.sh ($4,$5)
test.sh
#!/bin/bash
if [ $# != 5 ]; then
exit 1
fi
DIRDT=`date '+%Y%m%d'`
TSTDIR=$2/test/$DIRDATE
[ ! -d "$TSTDIR" ] && ( mkdir "$TSTDIR" || { echo 'mkdir command failed'; exit 1; } )
perl /home/dev/tstextr.pl -n $1 -b $2 -d $TSTDIR/ -s $3 -u $4 -p $5 -f $DIRDT
Is there any easy way to do this within the cron for those (2) input values? Thanks.
Alright try this way.
1) Create a separate file /mypath/dir/login.info
with content like this (username/password in separate lines):
foobar
F008AR
2) Modify your test.sh like this:
#!/bin/bash
if [ $# != 4 ]; then
exit 1
fi
DIRDT=`date '+%Y%m%d'`
TSTDIR=$2/test/$DIRDATE
[ ! -d "$TSTDIR" ] && ( mkdir "$TSTDIR" || { echo 'mkdir command failed'; exit 1; } )
IFS="
"
arr=( $(<$2/$4) )
#echo "username=${arr[0]} password=${arr[1]}"
perl /home/dev/tstextr.pl -n $1 -b $2 -d $TSTDIR/ -s $3 -u ${arr[0]} -p ${arr[1]} -f $DIRDT
3) Have your cron command like this:
30 10 * * 5 sh /home/test.sh hostnm101.abc /mypath/dir test login.info >> /logs/mytst.log 2>&1
Summary
- IFS stands for Internal Field Separator (IFS) in bash
I am using it like this:
IFS="
"
Which means make new line character as field separator (since we are storing username and password in 2 separate lines). And then this line to read file /mypath/dir/login.info
into an array:
arr=( $(<$2/$4) )
- First line (username) is read into
$arr[0]
- Second line (password) is read into
$arr[1]
You can echo it to check read content:
echo "username=${arr[0]}"
echo "password=${arr[1]}"
cron executes with sh -c so:
sh /home/test.sh hostnm101.abc /mypath/dir test `cat /mypath/dir/foobar_file` `cat /mypath/dir/F008AR_file` >> /logs/mytst.log 2>&
精彩评论