Eric Anderson Eric Anderson - 4 months ago 13
Bash Question

Bash Scripting: Using $( to assign variables

I am having the worst time with setting a variable in a bash shell using the $( format.

Here is what I have:

#!/bin/bash

var= date
echo $var

hrs="NA"
min="NA"
t="AM"
hr=12

var= date | grep -o [0-9][0-9]':'[0-9][0-9]
echo $var

if echo $var | grep -q [0-9][0-9] | > 12
then

echo $hrs
hrs=$(echo $var | grep -o "[0-9][0-9]")
echo $hrs
hrs="$hrs-$hr"
fi

echo $hrs

if $var | grep -q [0-9][0-9] | > 12
then
t="PM"
fi

echo $t


However when I echo the hrs variable afterwards it is an empty string. Can someone explain where I am going wrong with my assignment? I know that I am entering the if statement so I do not think that is the problem.

Answer

I guess you want something like this:

if [ `echo "$var" | grep -q [0-9][0-9]` -ge 12 ]
then
    hrs=$(echo "$var" | grep -o "[0-9][0-9]")
fi

In your code you should change

var= date | grep -o [0-9][0-9]':'[0-9][0-9]
#   ^                         ^ ^

for

var=$(date | grep -o '[0-9][0-9]:[0-9][0-9]')
#   ^^               ^                     ^^