0

I'm having trouble in finding the reason why my BASH script behaves differently if run alone or inside cron. I have this snippet:

    #!/bin/bash
    RESPONSE=$(curl -fs -XPOST -H "Content-type: application/json" -d '{"id" : 4}' https://myserver.com)
    echo $RESPONSE

    if [ -z "$RESPONSE" ]; then
        echo "empty response"
        return 0
    fi

    COMMAND=$(echo $RESPONSE | python -c "import sys, json; print json.load(sys.stdin)['command']")
    if [ -z "$COMMAND" ]; then
        echo "empty command"
    elif [ "$COMMAND" = "SYS_INFO" ];
    then
        #business logic
    fi

that prints two different responses in the two environments:

$RESPONSE Running from console:
{"id":"1f78d8d0-e754-4a23-a2f0-448fbeb42995", "key":"\n4RHDFAnTull1Z+aHGbO1zXcAGghuaEUz0w8sT7dlpc80jG6ZaWnbDox4G0f8sKY\ng0WZ80zWf8ftNgX3nes9MWYEq00nM5jJWCSavmGSKCKjoGD2XqBod8W0Z5w/KAHTSitGVMFgMjda91+xozw8uMlzR/t3Y8FP2k/NHj\n"}

$RESPONSE Running from :
{"id":"1f78d8d0-e754-4a23-a2f0-448fbeb42995", "key":"
4RHDFAnTull1Z+aHGbO1zXcAGghuaEUz0w8sT7dlpc80jG6ZaWnbDox4G0f8sKYj
g0WZ80zWf8ftNgX3nes9MWYEq00nM5jJWCSavmGSKCKjoGD2XqBod8W0Z5w/KAHTSitGVMFgMjda91+xozw8uMlzR/t3Y8FP2k/NHj
"}

Please notice the \n that the server returns into key field that are present when running from console and NOT present (actually, they are encoded as newline) when running from crontab

What I've tried:

  1. adding source ~/.bashrc as suggested here
  2. changing value of PATH evaluating the differences of the two environments as suggested here

However, nothing seems to work.

MarcoAbi
  • 61
  • 1
  • 6
  • 3
    Please include the code you use to run it. It sounds like in the latter case, you're running it with sh – that other guy Nov 05 '18 at 09:07
  • 1
    Why are you capturing the result into a variable at all? [You should quote the variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) and probably use `printf` instead of `echo` for proper portability; but really, just do `curl -fs -XPOST -H "Content-type: application/json" -d '{"id" : 4,}' https://myserver.com` without the variable capture. – tripleee Nov 05 '18 at 10:23
  • I've updated the question. When I'm running the code via console i'm using bash, when I'm running the script with cron I think i'm using bash as well... considering the hashbang value... I'm capturing the result since I'm parsing it later on (I'm using inline-python instead of other solution eg. jq) – MarcoAbi Nov 05 '18 at 15:32
  • Try `echo “$RESPONSE”` with double quotes. – Mark Setchell Nov 05 '18 at 15:51

0 Answers0