wakhaiha wakhaiha - 14 days ago 5
Linux Question

Automatically change variables in bash script

i have a script named variable.sh and contain set of many variables as per below:

var1=variable1
var2=variable2
var3=variable3
var4=variable4
var5=variable5


I need to run a command which will change the position of the variables in variable.sh. and the variables will keep changed when i run the command.It will become as below:

First change:

var1=variable2
var2=variable3
var3=variable4
var4=variable5
var5=variable1


Second change:

var1=variable3
var2=variable4
var3=variable5
var4=variable1
var5=variable2


Is there any possible command to do the above changes? i am using bash script in ubuntu. thank you

Answer

This can be done for example using Bash arrays:

#!/usr/bin/env bash

inputfile=/path/to/input

vars=()
values=()
while read line; do
    vars+=(${line%%=*})
    values+=(${line#*=})
done < "$inputfile"

values+=(${values[0]})
for ((i = 0; i < ${#vars[@]}; i++)); do
    echo ${vars[i]}=${values[i + 1]}
done > "$inputfile"
Comments