0

Hi guys I have the following function in linux script.

#!/bin/bash
function add1{
   echo $1
   var1=$1
   echo input + 1 is [$var1+1]
}
add 1

I want to take the input and add 1. So if the input was input_1 i want to return input_2. My code is currently printing input_1+1. I think this is because I am trying to add a integer to a string but i'm not sure of any other way I could do this. Can someone please point me in the right direction?

John
  • 59
  • 6
  • 1
    input_1 is of type string, how can you expect it to do normal integer type operations! – Am_I_Helpful Jun 25 '17 at 09:52
  • this is what i was thinking. So in this case it makes it impossible to do? – John Jun 25 '17 at 09:53
  • Try to change the [$var1+1] part with the built-in bash calculator expressions: `$(($var1 + 1))` or even `$(($1+1))` (you don't need `var1`). Also, the function name is `add1`, not `add`. – Diego Sevilla Jun 25 '17 at 09:53
  • @John - NO, it is not impossible. If the nature of the input will always be same, you can split the string at `_`, and add the numbers and again append with the splitted first-half. But, you've to do all of this using script. *(NOTE - I'm not a bash expert.)* – Am_I_Helpful Jun 25 '17 at 09:54
  • thank you @Am_I_Helpful I will try to split the string then. – John Jun 25 '17 at 09:55
  • See: [Counter increment in Bash loop not working](https://stackoverflow.com/q/10515964/3776858) – Cyrus Jun 25 '17 at 09:55

2 Answers2

2

I get a syntax error with your code because you missed a space, and then your function is named add1 but you call add. The function declaration should be:

function add {

However that is not POSIX compliant, add() { is preferred.

There are several ways to achieve what you are asking. Here is mine:

#!/bin/bash

add() {
   var1=$1
   num=${var1##*_}       # Extract the number after the _
   name=${var1%%_*}      # Extract the name before the _

   echo "input + 1 is: ${name}_$((num+1))"
}
add input_1

Gives:

input + 1 is: input_2

Note the arithmetic operation where I add 1 to num is $((num+1))

cdarke
  • 42,728
  • 8
  • 80
  • 84
  • 1
    If the input should support multiple `_`, e.g. `foo_bar_1`, then the name should be extracted with `name=${var1%_*}` (only single `%` in order to cut away the *shortest* match). This extracts `foo_bar`, whereas the solution with two `%%` would extract just `foo`. – weibeld Jun 25 '17 at 10:09
1

For a one-line solution:

function add() {
  echo "input + 1 is: ${1%_*}_$((${1##*_}+1))"
}
weibeld
  • 13,643
  • 2
  • 36
  • 50