Reputation: 183
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
Upvotes: 0
Views: 84
Reputation: 84652
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.
Upvotes: 1
Reputation: 786289
You can do this in BASH:
read -p "Enter a number " result_sort
((result_sort>2)) && result_sort+=" -n"
Upvotes: 1
Reputation: 9322
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:
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
.
The concatenation of two strings cannot be done in your way.
Upvotes: 1
Reputation: 1097
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.
Upvotes: 1