2

In my script I ask the user for some input and save it into some variables. Before using the strings in the variables I want to cut them if they are too long and add an ellipsis at the end. So I put all of the variables in an array and send them through a loop and an if statement and reasign the new value to the variable in the array. I have tried many ways and none have worked. The following being an example:

preset1="Short string"
preset2="Not long very string"
preset3="A very long string here which we will then cut"

presets=("${preset1}" "${preset2}" "${preset3}")

for x in "${presets[@]}"; do
    if [[ "${#x}" -gt 20 ]]; then
        y="${x:0:20}..."
        presets[$x]="$y"
    fi
done

Please help!

2 Answers 2

2

You have to loop over indexes of your array in order to change the values:

for x in "${!presets[@]}"; do
    str=${presets[$x]}
    (( ${#str} > 20 )) && presets[$x]="${str:0:20}..."
done

Works for associative and sparse arrays as well.


For variety, you can also use only parameter expansion like this:

for x in "${!presets[@]}"; do
    str=${presets[$x]}
    suffix=${str:20}
    presets[$x]=${str:0:20}${suffix:+...}
done
Sign up to request clarification or add additional context in comments.

5 Comments

This and the next solution work, but the variables e.g.: ${preset3} do not change. Using bash -x you can see that the string gets cut and the ellipsis added, but you can see that the value of the variable does not get updated if you do: echo ${preset3}.
@vato And why exactly would you like to do that? Isn't changing the array items enough?
@vato note that you can also use arrays directly with read: IFS= read -r 'array[0]'. You don't need variables at all. Just keep the array if it's more convenient for you.
I will try and explain what it is that I'm trying to achieve. In one part of the script I ask the user for the names of the presets. These presets cannot be too long because I use them in a little menu I print out for the user in a later step of the script. I could of course use an if statement for every preset and cut the strings there. I just thought, naively, that it might be easier putting everything in an array an use a for loop.
@vato I understand. But why not use just the array for everything? Why do you want to change even the variables. Creating menus will also be much easier using a list of options in an array.
1

You need to use the array[i] syntax to assign to array elements:

for ((i = 0; i < ${#presets[@]}; ++i)); do
    x=${presets[i]}
    if [[ "${#x}" -gt 20 ]]; then
        y="${x:0:20}..."
        presets[i]="$y"
    fi
done

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.