1

I have .sh script in UbuntuServer (VM):

response=$(curl -H 'Accept: application/vnd.twitchtv.v5+json' -H 'Authorization: OAuth 9f65dd6onr07vhpdqblbiix5rl0tch' -X GET 'https://api.twitch.tv/kraken/streams/127060528' | jq -r '.stream');
now=$(date +"%Y-%m-%d %T");
echo "$now" >> log.txt;
echo "$response" >> log.txt;
if [[ "$response" == "null" ]]
then
  echo "ZERO"
else
  streamlink -o "dump/stream_$now.mp3" twitch.tv/mahetirecords/clip/FreezingEncouragingCougarSuperVinlin audio
  echo "STREAM"
fi

When I run the script through the bash, the THEN-way is triggered. When I run the script through crontab, the ELSE-way is triggered. WHY?

Crontab -e:

* * * * * /home/chesterlife/twitch-interceptor/script.sh

If the stream is offline, then "$response" return null. This is text-null because var=""; if [ "$var" == "$response" ]; then echo "true"; else echo "false"; fi return false

Any ideas?

  • Often, the reason for a script behaving differently when run by cron compared to run by you in the shell is the environment — the job run through cron doesn't go through your profile (etc) to set the environment the way your interactive sessions get the environment set. This can be a big factor. – Jonathan Leffler Nov 13 '19 at 14:02
  • Do you include a shebang (`#!/bin/bash`) line at the top of the script? That may ensure that the script is run by Bash rather than `sh`). – Jonathan Leffler Nov 13 '19 at 14:03

2 Answers2

1

By default crontab executes using sh shell. You can change it to bash using the information from the link below:

https://unix.stackexchange.com/questions/94456/how-to-change-cron-shell-sh-to-bash

Also read this Stack Overflow question about the difference between [ and [[ in Bash

While [ is POSIX, [[ is only supported by some shells including bash.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Code Rage
  • 555
  • 3
  • 9
  • The script should have a proper shebang (this is basic good practice), but it could also easily be rewritten to run in a basic shell by switching to a single-bracket test command (and a single `=` for equality): `if [ "$response" = "null" ]`. Personally, I'd do both. – Gordon Davisson Nov 13 '19 at 18:52
0

You're missing a shebang in the script beginning, eg:

#!/usr/bin/env bash

Also, you should add your current user's path (obtained via echo $PATH) to your script, so you're running in a sane environnment, identical to your user's.

Orsiris de Jong
  • 2,819
  • 1
  • 26
  • 48