Bash for loop has syntax error only when run from

2019-08-01 06:14发布

I have a Ruby script that orchestrates a number of other scripts. One of the bash scripts pulls log data from a server, and a ruby script then parses them.

My bash script looks something like this:

#pullLogs.sh
for ((x = $2; x <= $3; x++)); do
    # creates a subdirectory for each server number
    rsync --progress -rvze ssh name@$ARCHIVE_SERVER:/path/to/log/$logDate.gz $x/
done
for ((x = $2; x <= $3; x++)); do
     cd $x
     for z in *.gz; do gunzip $z; done
     cd ..
done
cd ..

What this script does is pulls logs from a given date, from specified servers. Usually there are ten servers, so the script will pull from server 1, then from server 2, etc etc.

This script works perfectly if I specify the desired date from the command line

./pullLogs.sh desired_date 1 10

successfully pulls all the logs from the desired date from all ten servers.

However, I want to pull all the logs from todays date to some past date, and parse each one. So I use this ruby script:

while upload_day != $DESIRED_DATE do
    args = "#{year}#{month}#{day} 1 10"
    `bash -c ./#{path_to_pullLogs_sh} #{args}`
    `ruby #{name_of_followup_ruby_script}`
    upload_day = upload_day.prev_day 
end

The ruby script iterates through the correct days and calls the correct bash script (the one given above). However, after running the bash script, it produces an error:

./pullLogs.sh: line 15: ((: x = : syntax error: operand expected (error token is "= ")
./pullLogs.sh: line 21: ((: x = : syntax error: operand expected (error token is "= ")

So when I run it from the console, the loop variables 1 and 10 are good, but when I run it from the ruby script, it finds a problem with my syntax

How can make this work?

1条回答
虎瘦雄心在
2楼-- · 2019-08-01 06:37

Drop the -c from your call to bash. This causes ./#{path_to_pullLogs_sh} to be used as the command to run, and the following arguments are passed as shell arguments starting with $0, not $1, meaning your script is short one argument.

`bash ./#{path_to_pullLogs_sh} #{args}`

(This works for the same reason as Z1MM32M4N's comment; it causes bash to treat ./pullLogs.sh as a script to run, rather than a string containing a snippet of shell code to execute.)

查看更多
登录 后发表回答