1

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?

2 Answers 2

1

It looks like you are implementing the select built-in command:

PS3="What would you like to execute?: "
select cmd in *; do
    $cmd
    break
done
Sign up to request clarification or add additional context in comments.

Comments

0

You must use the eval command:

eval \$a0

Hope this helps =)

EDIT: Fixed missing backslash

2 Comments

Thanks Janito! That worked, except I needed to modify it like: eval \$a$(echo $num)
No problem, and thanks for the observation! Could you consider accepting the answer, please? =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.