Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `${1#*=}` mean in Bash?

I found an awesome answer on StackOverflow which explains how to pass an associative array to a function. Would someone be able to help me figuring out what the syntax of ${1#*=} in the code below specifies? (Borrowed from that answer by jaypal singh):

#!/bin/bash

declare -A weapons=(
  ['Straight Sword']=75
  ['Tainted Dagger']=54
  ['Imperial Sword']=90
  ['Edged Shuriken']=25
)

function print_array {
    eval "declare -A arg_array="${1#*=}
    for i in "${!arg_array[@]}"; do
       printf "%s\t%s\n" "$i ==> ${arg_array[$i]}"
    done
}

print_array "$(declare -p weapons)"

Here's my guess so far (correct me if I'm wrong on any of these):
- 1 means the first parameter passed to the function ($1 or ${1})
- # means the index of $1, which, since $1 is an associative array, makes # the keys of $1
- * means the values of of the # keys in associate array $1

That leaves the =. What does that signify? Is that like a way to show that you want # and * to mean the keys and values of the associate array?

like image 592
GreenRaccoon23 Avatar asked Dec 09 '22 02:12

GreenRaccoon23


1 Answers

The snippet ${1#*=} has nothing to do with associative arrays.* (Bash's syntax is super consistent, and not at all confusing)

This is a pattern match on the value of the first argument (${1}) of your function or script. Its syntax is

${variable#glob}

where

  • variable is any bash variable
  • glob is any glob pattern (subject to pathname expansion) to match against)

It deletes the shortest match, starting at the beginning of the line. There is also ## which deletes the longest match starting from the beginning of the variable, %, which deletes the shortest match starting from the end, and %%, which deletes the longest match starting from the end.


So, for example, the following code:

myVar="abc=llamas&disclaimer=true"
echo "${myVar#*=}"

will print llamas&disclaimer=true to the screen.

On the other hand,

myVar="abc=llamas&disclaimer=true"
echo ${myVar##*=}

will print true, and

myVar="foobar is bad"
echo "${myVar%%b*}"

will print foo


* This is fully explained in the bash man page; just search for the string ${parameter#word} to find it

like image 123
jpaugh Avatar answered Dec 25 '22 22:12

jpaugh