You might be tired by finding the right Bash shell script to run more commands which are stored in a file. Here is the script which you are searching…
In this example going to use below commands in the file to execute using the script.
df -h
uname -a
ls -l
netstat
As next step, we are going to create a file with above commands assigned to a variable. If we are using this commands directly without assigning to a variable, the script will not execute the commands properly. Because of space(df -h) which we used in between commands will be taken as a separator by the script. So that only we are saving the commands in a variable.
[root@server ~]# cat > cmd.lst DF=`df -h` UNAME=`uname -a` CAT=`cat /etc/resolv.conf` NET=`netstat` ^c [root@server ~]#
Then create the script to run the commands which are stored in cmd.lst file
[root@server ~]# cat > cmdscritp.sh #!/bin/bash sh cmd.lst for comm in `cat cmd.lst` do for cmd in `cat cmd.lst | awk -F "=" {'print $1'}` do echo "Going to execute:" $cmd eval $cmd if [[ $? -eq "0" ]] then echo $cmd "executed successfully..." else echo "last command didn't executed properly. So, Exiting from the script..." exit fi done done
and now provide the execute permission using chmod command for both files.
[root@server ~]# chmod +x cmd.lst [root@server ~]# chmod +x cmdscritp.sh [root@server ~]# ll | grep cmd -rwxr-xr-x. 1 root root 69 Dec 28 23:58 cmd.lst -rwxr-xr-x. 1 root root 326 Dec 28 23:58 cmdscritp.sh
Now run the script
[root@server ~]# ./cmdscript.sh cmd.txt: line 4: netstat: command not found cmdscript.sh cmd.txt diff2.sh diff.sh lvcheck.txt post pre sh Goind to execute: df Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 10474496 2097740 8376756 21% / devtmpfs 1887604 0 1887604 0% /dev tmpfs 1894500 0 1894500 0% /dev/shm tmpfs 1894500 8444 1886056 1% /run tmpfs 1894500 0 1894500 0% /sys/fs/cgroup tmpfs 378900 0 378900 0% /run/user/0 tmpfs 378900 0 378900 0% /run/user/1000 df executed successfully... Goind to execute: uname Linux uname executed successfully... Goind to execute: ls cmdscript.sh cmd.txt diff2.sh diff.sh lvcheck.txt post pre sh ls executed successfully... Goind to execute: net ./cmdscript.sh: line 8: net: command not found last command didnt executed properly. So, Exiting from the script...
Script working successfully. Thanks for reading the post and support.