1

I'd like to understand bash a bit better as I'm apparently horrible at it...

I'm trying to generate a sequence of constant width integers, but then test them to do something exceptional for particular values. Like so:

  for n in $(seq -w 1 150)
  do
    # The next line does not work: doit.sh: line 9: XX: command not found
    #decval= $( echo ${n} | sed 's/^0//g' | sed 's/^0//g' )
    #if [[ ${decal} -eq 98 ]] ; then
    if [[ $( echo ${n} | sed 's/^0//g' | sed 's/^0//g' ) -eq 98 ]] ; then
      echo "Do something different for 98"
    elif [[ $( echo ${n} | sed 's/^0//g' | sed 's/^0//g' ) -eq 105 ]] ; then
      echo "Do something different for 98"
    fi
  done

This script works for my purposes, but if I try and make the assignment 'decval= $(…' I get an error 'command not found'. I don't understand this, can someone explain?

Also, is there an improvement I can make to this script if I have a large number of exceptions to prevent a long list of if ; then elif … ?

1
  • It's probably easier to generate variable width, then convert to fixed width with a simple printf. For additional improvements, have a look at the shell's case statement. Commented Jan 18, 2014 at 18:00

1 Answer 1

6

The problem is in the space between = and $:

decval= $(…

You should write without spaces:

decval=$(...

Because, if you write the space, your shell reads decval= as declval="" and treats the result of $(echo...) as the name of a command to execute, and obviously it doesn't find the command.

Also (just a small optimization), you can write:

sed 's/^0\+//'

instead of

sed 's/^0//g' | sed 's/^0//g'

Here:

  • 0\+ means 0 one or more times;
  • g is removed, because g means replace all occurences in the string, and you have only one occurence (^ can be only one time in a string).

Also, you can check your variable even with leading zeros, without sed:

[[ "$n" =~  "0*98" ]]
Sign up to request clarification or add additional context in comments.

2 Comments

Or even sed 's/^0*//' which should be portable to pretty much any platform.
I could have sworn I'd tried that… so of course I didn't try it 'again'. D'Oh!

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.