PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 20, 2022

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

 December 20, 2022     arrays, associative-array, bash, syntax, variables     No comments   

Issue

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?


Solution

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



Answered By - jpaugh
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing