faizan
faizan

Reputation: 304

What does ${!variable:0:1} mean in bash?

I've been reading a script and come across a point where it goes beyond my understanding. The snippet from the code is below:

while getopts ":h-:" OPTION; do
        case "$OPTION" in
         -)
                case "$OPTARG" in
                   time)  
                        if [ ! -z "${!OPTIND:0:1}" -a ! "${!OPTIND:0:1}" = "-" ]; then
                        Time="${!OPTIND}"
                        OPTIND=$(( $OPTIND + 1 ))
                        fi ;;
                 esac
                ;;
        h)      Usage 0;;

# More code

       esac
done
shift $((OPTIND - 1))

The point where I'm struggling with is the if condition. What does it actually mean?

I know about the getopts and the relevant variable OPTIND and OPTARG it provides, but quite struggling to find out what condition is being fulfilled by the if statement.

If anyone can explain that to me, it would be really helpful.

Thanks in advance

Upvotes: 1

Views: 3182

Answers (1)

Ivan
Ivan

Reputation: 7287

Let's suppose you have these vars:

foo=bar
bar=0123456789

Code

echo ${!foo}
0123456789

will give you the value of $bar! This called indirect expansion. And this code:

echo ${bar:0:3}
012

will return first 3 symbols of $bar This is like slices in python. Now let's combine these commands:

echo ${!foo:0:3}
012

We get first 3 symbols of $bar

Upvotes: 6

Related Questions