devd devd - 3 months ago 7
Bash Question

Meaning of @# in shell

I recently got this script to match a string in command line aguments:

if [[ "$@" == "${@#foo}" ]]; then echo "not found" ; else echo "found"; fi


Looks like it does negative search. What is the meaning of
@#
exactly?

Answer

from man bash under Parameter Expansion:

${parameter#word}

${parameter##word}

Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameā€ ter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

the $@ is expanded to the list of script arguments each enclosed into quotes: "$1" "$2" "$3"...

thus the "${@#foo}" would expand to a list of quoted script arguments with stripped out prefix foo if such prefix exist in any of expanded strings, i.e. the script test:

#!/bin/bash
echo "${@#foo}" 

invoked as:

./test abc foodef

outputs

abc def