Shellscript: Pmset value as variable in else if script

356 views Asked by At

I'm trying to write a shellscript that will change the hibernation mode from 3 to 25 and vice versa on a Mac. I try to set the result of the "pmset -g | grep hibernatemode" command as the OUTPUT variable (which gives either "hibernatemode 3" or "hibernatemode 25" result depending on the power source) and set the HIBERNATE variable to "hibernatemode 3". So if the variable OUTPUT and HIBERNATE match I want it to execute a command which will change that system setting but for now I just want it to display which one it is using the echo command. The problem is whatever I do and whatever the value of OUTPUT is I get "hibernatemode 25" as a result. I'm really new to this so there may be a very basic thing I'm missing. Thanks for the help!

#!/bin/bash

OUTPUT="$(pmset -g | grep hibernatemode)"
HIBERNATE="hibernatemode 3"

echo $OUTPUT
echo $HIBERNATE

if [ $OUTPUT = $HIBERNATE ]
  then 
echo hibernatemode is 3
  else
echo hibernatemode is 25
fi
1

There are 1 answers

1
Gabriel Gyarmati On

Ok, I figured it out. The problem was that the output of the shell command had a TAB instead of SPACE. I copied the output from running the command straight from the Terminal. The working shellscript looks like this, if anybody needs it:

#!/bin/bash

OUTPUT="$(pmset -g | grep hibernatemode)"
HIBERNATE3=" hibernatemode        3"
HIBERNATE25=" hibernatemode        25"

if [ "$OUTPUT" = "$HIBERNATE3" ]

 then 
  pmset -b hibernatemode 25
  echo Hibernatemode set to 25 - DISK

elif [ "$OUTPUT" = "$HIBERNATE25" ]

 then
  pmset -b hibernatemode 3
  echo Hibernatemode set to 3 - RAM

else
  echo Unsuccessful!

fi