Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Bad substitution error with a Shell Script on a mac?

I'm getting an error message "./query.sh: line 5: ${1,,}: bad substitution" whenever I run a shell script in a Mac OSX terminal

#!/bin/bash
dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

if [ "$1" != "" ]; then
    letter1=$(echo ${1,,}|(cut -b1))new
    if [[ $letter1 == [a-zA-Z0-9] ]]; then
        if [ -f "$dir/data/$letter1" ]; then
            grep -ai "^$1" "$dir/data/$letter1"
        else
            letter2=$(echo ${1,,}|cut -b2)
            if [[ $letter2 == [a-zA-Z0-9] ]]; then
                if [ -f "$dir/data/$letter1/$letter2" ]; then
                    grep -ai "^$1" "$dir/data/$letter1/$letter2"
                else
                    letter3=$(echo ${1,,}|cut -b3)
                    if [[ $letter3 == [a-zA-Z0-9] ]]; then
                        if [ -f "$dir/data/$letter1/$letter2/$letter3" ]; then
                            grep -ai "^$1" "$dir/data/$letter1/$letter2/$letter3"
                        fi
                    else
                        if [ -f "$dir/data/$letter1/$letter2/symbols" ]; then
                            grep -ai "^$1" "$dir/data/$letter1/$letter2/symbols"
                        fi
                    fi
                fi
            else
                if [ -f "$dir/data/$letter1/symbols" ]; then
                    grep -ai "^$1" "$dir/data/$letter1/symbols"
                fi
            fi
        fi
    else
        if [ -f "$dir/data/symbols" ]; then
            grep -ai "^$1" "$dir/data/symbols"
        fi
    fi
else
    echo "[*] Example: ./query [email protected]"
fi

The scripts function is to search throuhg a huge number of data files so could anybody help me pinpoint the source of the problem ?

like image 453
Random person Avatar asked Dec 14 '17 14:12

Random person


1 Answers

The ,, operator was introduced in bash 4.0, but /bin/bash on macOS is still version 3.2. You can install a newer version of bash and change your shebang accordingly, or you can use letter1=$(echo "$1" | tr '[:upper:]' '[:lower:]' | cut -b1) instead.

(You can, however, use ${letter:0:1}, ${letter:1:1}, etc, in place of a call to cut to get a single letter from the string.)

My advice is to treat /bin/bash on macOS as nothing more than a POSIX-compatible shell. Use #!/bin/sh if you want a portable script, or use #!/usr/local/bin/bash (or whatever is appropriate, after installing a new version of bash) if you want to take advantage of bash extensions at the expense of portability.

like image 64
chepner Avatar answered Nov 15 '22 03:11

chepner