Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SH script string concatenation not working

Tags:

sh

I have a bash script I'm writing that is not concatenating a string as expected. I have (in the script) a preset list of folder paths in a single string, separated by a single space. This works great, later on in the script, I can cycle through each folder path as expected.

I am trying to allow the user to enter in an optional list of other folders, and add to the list of paths to check for. Below is my code, and the output of the command:

#!/bin/sh
MOUNTPOINTS="/ /var /var/moodledata2"   #Set the mount points to check for

while getopts ":dh" opt; do
        case $opt in
                d)
                        DEBUG=true
                        ;;
                h)
                        echo USAGE: diskspace \[-d\] \[\/path1 ...\]
                        exit 0
                        ;;
                \?)
                        echo Incorrect syntax
                        ;;
        esac
        shift $((OPTIND - 1))
done

if [ "$#" -gt 0 ]; then
        for var in $@; do
                NEWMOUNTPOINTS .= $var
                echo "${MOUNTPOINTS} ${var}"
                echo "${NEWMOUNTPOINTS}"
        done
fi

When running the command...

$ ./dt /home
./dt: 22: ./dt: NEWMOUNTPOINTS: not found
/ /var /var/moodledata2 /home

I originally tried with MOUNTPOINTS .= ${var} and MOUNTPOINTS .= "${var}", but they still produce the same error. I thought I could create a new variable, but that didn't work either (as shown above). The rest of the script continues on, but only with the original MOUNTPOINTS at the top; it never changes that, even if I use MOUNTPOINTS .= $var, above.

What can I do to get a dynamic string created with the command line arguments supplied?

like image 380
Canadian Luke Avatar asked Jul 15 '26 03:07

Canadian Luke


1 Answers

NEWMOUNTPOINTS="${NEWMOUNTPOINTS} ${var} "

This should concatenate the variable.

like image 176
jftuga Avatar answered Jul 17 '26 17:07

jftuga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!