-1

I have this simple bash script called get-volume.sh:

mutedStatus=`amixer -c 0 -D pulse get Master | tail -n 1 | grep -c '\[on\]'`

echo $mutedStatus

if "$mutedStatus" -eq 0; then
    echo 'x'
else
    echo `amixer get Master | awk -F'[]%[]' '/%/ {if ($7 == "off") { print "MM" } else { print $2 }}' | head -n 1`
fi

exit 0

It should

  1. populate the mutedStatus variable with 1 if unmuted and 0 if muted
  2. if muted, echo 'x', else echo the volume
  3. exit

But when I run the script with bash get-volume.sh I get this irritating message:

1
get-volume.sh: line 7: 1: command not found
100

why is it giving that error?

It seems to be trying to execute my variable, which is where 1: comes from, as when I mute my system the message changes to

get-volume.sh: line 7: 0: command not found
Bassie
  • 9,529
  • 8
  • 68
  • 159
  • 1
    I think it's just a simple syntax error. See https://acloudguru.com/blog/engineering/conditions-in-bash-scripting-if-statements – user2740650 Dec 31 '21 at 23:53
  • 1
    Looks like you figured it it out. BTW the command at line 3 is invoked immediately at line 3, not when the variable is referenced as you seemed to indicate. – user2740650 Dec 31 '21 at 23:56
  • 2
    `-eq` is not a *shell* operator; it's an argument to be interpreted by the `test` command. You are literally trying to run a command named `1` with arguments `-eq` and `0`. – chepner Dec 31 '21 at 23:57
  • The condition in a shell `if` statement is a *command*, not an expression. The condition is true if the command succeeds, false if it fails. `[` is a special (often built-in) command that evaluates an expression. – Keith Thompson Dec 31 '21 at 23:59
  • BTW `#!.bin/bash` should be: `#!/bin/bash` – user3439894 Dec 31 '21 at 23:59
  • @KeithThompson. `[` is a builtin command in `bash` – fpmurphy Jan 01 '22 at 02:35

1 Answers1

0

Solution is to write the if statement like this

...
if [ "$mutedStatus" -eq 0 ] ; then
...

Notice the space after [ and before ] - without this the command fails with

get-volume.sh: line 7: [1: command not found

chepner
  • 497,756
  • 71
  • 530
  • 681
Bassie
  • 9,529
  • 8
  • 68
  • 159
  • Other ways of writing the `if` statement include `if test "$mutedStatus" -eq 0`, `if [[ "$mutedStatus" -eq 0 ]]`, `if (( mutedStatus == 0 ))` , and `if let "mutedStatus == 0"` and many more. However for portability, one such use the Posixly correct war, i.e. `if [ "$mutedStatus" -eq 0 ]` – fpmurphy Jan 01 '22 at 03:22