0

I'm asking the user to enter a number and if the number is greater than 2 then I like to add the string -n to that number. Here's my code:

read -p "Enter a number " result_sort
if [ $result_sort >2 ]; then

   result_sort = $result_sort + " -n"

fi

echo "$result_sort" 

I'm getting the error: command not found

4 Answers 4

1

Your code should look like this:

read -p "Enter a number " result_sort
if [ $result_sort -gt 2 ]; then

   result_sort=$(echo "$result_sort -n")

fi

echo "$result_sort" 

There were two mistakes:

  1. The test utility ([) you used doesn't accept < and > as greater and less. Those characters are redirection characters (see I/O Redirection) in the shell. Your statement in the if clause is always true, even if $result_sort is less than 2. You are writing the result of that command [ $result_sort ] to a file called 2.

  2. The concatenation of two strings cannot be done in your way.

Sign up to request clarification or add additional context in comments.

Comments

1

try this

result_sort=`echo "${result_sort} -n"`

there should be no space between the result_sort and the "=" sign. In your case because of the space, it identifies result_sort as a command and tries to interpret it.

Comments

1

You can do this in BASH:

read -p "Enter a number " result_sort

((result_sort>2)) && result_sort+=" -n"

Comments

1

The result can be accomplished simply by concatenating the string values of the variables:

read -p "Enter a number " result_sort

[ "$result_sort" > 2 ] && 
result_sort="${result_sort}-n"

echo "$result_sort" 

brace protecting the variable can prevent ambiguity. Also using the arithmetic comparison given by anubhava can protect against users entering something other than numbers.

Comments

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.