Home > Mobile >  Execute number of commands from a text file
Execute number of commands from a text file

Time:12-19

I have the below script which need to get the output for the command where I am not able to get the output for the commands which has space Ex: "cat test.txt"

Need to execute 1000 commands for a server. Need to apply a script as below and expected the output as below.

****Script: **

#!/bin/sh
a=`whoami`"@"`hostname`":~$"

IFS=''
while read line; do

command=$line
b=line
for command in $line
do
        echo $a "$command"
        `$command`
        echo $a
done
done < test.txt

**Out I m getting as below:**

rootjey@C-2PZ1DK3:~$ ls
forloop.sh  scripts.sh  test.sh  test.txt
rootjey@C-2PZ1DK3:~$
rootjey@C-2PZ1DK3:~$ pwd
/tmp
rootjey@C-2PZ1DK3:~$
rootjey@C-2PZ1DK3:~$ date
Fri Dec 16 19:29:35 IST 2022
rootjey@C-2PZ1DK3:~$
rootjey@C-2PZ1DK3:~$ cat test.txt
forloop.sh: 12: cat test.txt: not found
rootjey@C-2PZ1DK3:~$

**Expected output**

rootjey@C-2PZ1DK3:~$ ls
forloop.sh  scripts.sh  test.sh  test.txt
rootjey@C-2PZ1DK3:~$
rootjey@C-2PZ1DK3:~$ pwd
/tmp
rootjey@C-2PZ1DK3:~$
rootjey@C-2PZ1DK3:~$ date
Fri Dec 16 19:29:35 IST 2022
rootjey@C-2PZ1DK3:~$
rootjey@C-2PZ1DK3:~$ cat test.txt
**Here it should open the contents of the file**
rootjey@C-2PZ1DK3:~$

for the single commands, it is getting executed but for the commands which has spaces in between is not able to retrieve.

Please help with a solution or hint.

CodePudding user response:

To start, you need to remove that IFS definition.

You should have only one logical command per input line, i.e.

du -s * 2>>/dev/null | awk 'BEGIN{ sum=0 ;}{ sum=sum $1 ; }END{ print sum ; }'

Also, you can define any string as divider.

You forgot to escape the dollar sign in your definition of "a".

You didn't need the "for" loop. It really serves no purpose.

The proposed revision of the script is as follows:

#!/bin/bash
a=`whoami`"@"`hostname`":~\$"

while read command
do
    echo -e "\n###############################################################\n$a $command"
    eval ${command}
done < test.txt
echo $a

Given the number of commands to be executed (hopefully not inter-dependant), you might want to consider adding a count-down to get a sense of how many lines remaining for completion of the batch sequence.

If inter-dependant, you might want to consider adding a test before each command execution, something like

if [ -f ${COMMAND_NUMBER}.success ]

in order to skip that command on a second or third run of the same script with the same input file, but to abandon if $? is not equal to zero.

  • Related