Reputation: 31
So, I'm really new to writing scripts but really enjoying it. For a class I am currently taking the instructor is asking that we provide a log file of all the commands we use in our labs. Up until now, I have just been doing history > file.txt. The problem with that method for me is that it is also logging a ton of my typos. I could just keep doing it that way because it doesn't affect my grade at all but I'm eager to learn as much as I can.
Anyways, I am hoping to come up with something to sort and log my successful commands as I go. I wrote a script that kinda does it but it costs me a lot of functionality. I was hoping to get some help to point me in the right direction.
#!/bin/bash
logger(){
read usr_command
$usr_command
exit_code=$?
if [ "$exit_code" -eq 0 ]; then
echo "yea"
else
echo "nah"
fi
}
while true; do
logger
done
Obviously, I need to write instructions to pass the commands to a file once they been analyzed but what I'm really looking for is a way to do this without passing my commands through read
. I can't seem to get the script to recognize the exit code of the commands I want because every time it runs it just catches the successful command that executes the script.
Thanks in advance for looking over my amateur skills and sorry if I wasted anyone's time.
Upvotes: 3
Views: 310
Reputation: 7220
In regards to lost functionality, something like rl-wrap might help.
Instead of making your own REPL, you could prepend a function call to each command like this:
ok() {
"$@"
test $? -eq 0 && echo "$*" >> successful-commands.txt
}
ok true # logged
ok false # not logged
In this way, your question is similar to:
Upvotes: 1