John
John

Reputation: 59

how to increase part of a variable in linux

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?

Upvotes: 0

Views: 74

Answers (2)

weibeld
weibeld

Reputation: 15242

For a one-line solution:

function add() {
  echo "input + 1 is: ${1%_*}_$((${1##*_}+1))"
}

Upvotes: 1

cdarke
cdarke

Reputation: 44354

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))

Upvotes: 2

Related Questions