Calling variables to run scripts

Posted by user1416419 on Stack Overflow See other posts from Stack Overflow or by user1416419
Published on 2012-09-30T03:28:03Z Indexed on 2012/09/30 3:37 UTC
Read the original article Hit count: 71

Filed under:
|

I have a script that lists all files in a directory, lists them in alphabetical order, and places the number of the file before the filename.

#!/bin/bash

x=1
cd ~/bin

for f in *
do
    if [ -f $f ]; then
        echo "$x: $f"
        declare a$x=$f
        x=$(expr $x + 1)
    fi
done

read -p "What would you like to execute?: " num
$num

Output would be

1: file0
2: file1
3: file2

etc

Running $num will execute the command

a1

which is not a command. What I want to do is run what $a1 is equal to (ie file0). How can I do this?

© Stack Overflow or respective owner

Related posts about linux

Related posts about bash