0

I am a Bash noob and would like to learn how to do this. Objective: Write a bash script, that runs commands that are listed in a .txt file, check if the command worked, if yes output in a file, if no skip this command.

I have a folder named /scripts and inside this folder I have 2 files commands.txt and compiler.sh

commands.txt has the the commands that I would like to run on my script. Below is what I currently have saved on this file.

#ServerInformation
hostname
lscpu
lshw
hwinfo
lspci
lscsi
lsusb
inxi
lsblk
df
fdisk -l
mount | column -t
free -m
dmidecode
sudo cat /proc/cpuinfo
sudo cat /proc/meminfo
fakecommand

#NetworkInformation
ifconfig

and here is compiler.sh

#!/bin/bash
cat commands.txt | while read -r line
do
echo "Running Command $line"
"$line"

if [ "$?" -ne 0 ]
   then
      echo "The command $line does not exist. Skipping."
   else
        echo "$line" >> datacollect.txt
        "$line" >> datacollect.txt
        echo ""
        echo ""
   fi

done

I am having problems with the command that uses "Cat" as I am getting this error: compiler.sh: 5: compiler.sh: sudo cat /proc/cpuinfo: not found

If anyone knows, how do I get around this problem? also why is this problem happening?

Thank you in advance!

Edit I found that fdisk -l is also getting this problem. so not only the Cat commands. Could the "space" be the problem?

Thank you!

bujom
  • 41
  • 5
  • If you want your commands to be parsed _as code_, you need to use `eval` to start them. Taking out the quotes will get you something that looks like it works for some of the simpler commands, but the ones with pipes (`mount | column -t`) won't work without being fully parsed. – Charles Duffy Sep 30 '22 at 17:03
  • See [BashFAQ #50](https://mywiki.wooledge.org/BashFAQ/050) for background on why changing `"$line"` to `$line` isn't enough, and [BashFAQ #48](https://mywiki.wooledge.org/BashFAQ/048) for why what you're doing here should only be a last resort. – Charles Duffy Sep 30 '22 at 17:06
  • (`"$line"` is looking for something like `/usr/bin/fdisk -l`, with the space, the dash, etc. all as part of the filename; you may have a `fdisk` executable, but you almost certainly don't have a `fdisk -l` executable) – Charles Duffy Sep 30 '22 at 17:07
  • Hello @CharlesDuffy Eval works wonders. I thank you for sharing the BashFAQ link, and as well as the explanation. – bujom Sep 30 '22 at 17:22
  • BTW, do be sure you're running `eval "$line"`, not `eval $line`; the failures with the latter code are subtle but very real. Also, [Why is testing `$?` to see if a command succeeded or not an antipattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – Charles Duffy Sep 30 '22 at 17:36
  • Thanks for the reminder. Yes I have it as eval "$line" currently. – bujom Sep 30 '22 at 19:51
  • I will check this link that you have shared as well. Thanks again!! – bujom Sep 30 '22 at 19:57

0 Answers0