confusified
confusified

Reputation: 2330

Command not acting properly in script

The command:

value=${value%?}

will remove the last character from a variable. Is there any logical reason why it would not work from within a script? In my script it has no effect whatsoever.

if [[ $line =~ "What I want" ]]
    then
            if [[ $CURRENT -eq 3 ]]
            then
                    echo  "line is " $line 
                    value=`echo "$line" | awk '{print $4}'`
                    echo "value = "$value   
                    value=${value%?}
                    echo "value = $value "

                    break
            fi
fi

I cant post the whole script, but this is the piece I refer to. The loop is being entered properly, but the 2 echo $value lines return the same thing.

Edit - this question still stands. The code works fine line bu line in a terminal, but all together in a script it fails.

Upvotes: 1

Views: 66

Answers (2)

Since you have provided only the relevant part in the code and not the whole file, I'm going to assume that the first line of your file reads `#!/bin/sh'. This is your problem. What you are trying to do (parameter expansion) is specific to bash, so unless /bin/sh points to bash via a symlink, then you are running the script in a shell which does not understand bash parameter expansion.

To see what /bin/sh really is you can do: ls -l /bin/sh. And to remedy the situation, force the script to run in bash by changing the `shebang' at the top to read `#!/bin/bash'

Upvotes: 0

tamasgal
tamasgal

Reputation: 26259

Echo adds an extra line character to $value in this line:

value=`echo "$line" | awk '{print $4}'`

And afaik that extra char is removed with %?, so it seems it does not change anything at all.

Try echo -n instead, which does not add \n to the string:

value=`echo -n "$line" | awk '{print $4}'`

Upvotes: 2

Related Questions