How to execute a command inside a while loop?

How do we execute a command inside a while loop?

while <condition>; do
  <command>
done

Example:

$ i=0
$ while ((i++ < 3)); do
>   echo $i
> done
1
2
3

hey sorry, i wrote the description but don't lnow how it got erased.

i have a set of commands inside a text file. 1 command per line.
command.txt

echo "start"
ls -l
pwd

i want to execute these commands one by one and after finishing the last command, again it should start from the 1st command.

infinity.sh

count=0
while :
do
        while read exe_command
        do
                (( count++ ));
                echo "$exe_command"
                result_$count=`$exe_command`
        done < command.txt
        echo ""
done

the commands are not getting executed.

output:
e

cho "start"
infinite.sh: line 8: result_178="start": command not found
ls -l
infinite.sh: line 8: result_179=total: command not found
pwd
infinite.sh: line 8: result_180=/home: No such file or directory

The easiest way is:

sh command.txt

I don't think that will work.
Its a txt file. sh cannot run a .txt file

Have you tried it?

1 Like

So, you are trying to set a variable variable name then. Have you considered using an array?

#!/bin/ksh93
set -A result

count=0
while :
do
        while read exe_command
        do
                (( count++ ));
                echo "$exe_command"
                result[$count]=`$exe_command`
        done < command.txt
        echo ""
done

for i in 1 2 3 4 5
do
   echo "Result for $i is ${result[$i]}"
done

Of course, this is assuming that you have a simple value to store in your variable. The output you have given us suggests that you want to store the output from ls -l in a variable. I'm not really sure that is a good thing to attempt.

Are you actually after storing the return code instead? In that case, change the line:-

            result[$count]=`$exe_command`

to be:-

            $exe_command
            result[$count]=$?

There is also a limit to the number of items in the array, 0-1023 in ksh, 4 million in ksh93. Not sure on the bash limit.

WARNING - your logic is dangerous.

Imagine if someone could infect your input file and add any of the following:-

shutdown -t 0
rm /etc/inittab
rm -r /etc/rc.d
rm /etc/passwd
rm -r /

I hope that this helps / gives you something bigger to consider.

Robin

1 Like

If you really want the shell to compute variable names:

eval result_$count=`$exe_command`
1 Like