-1

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.

5
  • 2
    You have several errors in this code. What is it you are trying to accomplish?
    – chepner
    Commented Feb 26, 2013 at 19:25
  • var= date must be var=date etc. Commented Feb 26, 2013 at 19:34
  • @Fredrik: More likely it needs backticks (which I'm too lazy to figure out how to render in a comment). Commented Feb 26, 2013 at 19:36
  • 1
    In several places, you seem to be missing backticks and/or quotation marks. Please copy-and-paste the exact contents of your script and its output into your question. Without that, we can only guess what you're trying to do. Commented Feb 26, 2013 at 19:37
  • @KeithThompson - you're right, I was merely refering to the space after the =-sign. $(...) is prefered over backticks. Commented Feb 26, 2013 at 19:38

1 Answer 1

1

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]')
#   ^^               ^                     ^^
3
  • 1
    I think you're on the right track for figuring out the OP's question, but why backticks in one place and $() in the other? grep -q isn't going to work with -ge, either.
    – Carl Norum
    Commented Feb 26, 2013 at 19:29
  • Good point. I just copied the original code with $( and then added my part with backsticks. I prefer backsticks
    – fedorqui
    Commented Feb 26, 2013 at 19:29
  • 1
    You really should have quotes around the entire regexp; if you happen to have files with names like 12:34 in your current directory [0-9][0-9]':'[0-9][0-9] will expand to a list of matching files. I just fixed it. Commented Feb 26, 2013 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.