Run multiple command line scripts and redirect their outputs on Linux

Recently, I had a situation where I needed to run multiple command line scripts on Linux at the same time while redirecting their outputs to separated log files and wait for them to finish.

If you ever need to do something like that, I leave here the command line script that I used to accomplish this task:

#!/bin/bash

# Add the full path processes to run to the array
PROCESSES_TO_RUN=("/home/joao/Code/test/prog_1/prog1" \
                  "/home/joao/Code/test/prog_2/prog2")
# You can keep adding processes to the array...

for i in ${PROCESSES_TO_RUN[@]}; do
    ${i%/*}/./${i##*/} > ${i}.log 2>&1 &
    # ${i%/*} -> Get folder name until the /
    # ${i##*/} -> Get the filename after the /
done

# Wait for the processes to finish
wait

Automating stuff with shell scripts (Including MySQL commands)

more-like-linux-wallpaper

Yesterday I was debugging a C project that stores a lot of data in the filesystem and in a MySQL database. And I found myself repeating the same commands everything I fixed something and restarted the application. Those commands where:

$ rm -rf debug_*
$ rm -rf data && mkdir data
$ mysql -u root -proot
mysql> USE db_name;
mysql> DELETE FROM table_name WHERE id > 0;
mysql> quit

And believe me, after a while you get really fast at this… but it’s still unnecessary!!

So I decided to create a shell script called clean.sh to automate this process. And, while the first commands are really straightforward, running MySQL commands, in a shell script, it’s a little bit more complex if you are not used to do it through the command line!

So, if you ever need to do something like this, here is my script:

#!/bin/bash
# Clean data script
rm -rf data \
&& mkdir data \
&& mysql -u root -proot -Bse "USE db_name;DELETE FROM table_name WHERE id > 0;" \
&& rm -rf debug_* \
&& echo "Cleaned!"

After saving your file with this content on it, you just need to give execution permissions and run it!

$ chmod 755 clean.sh
$ ./clean.sh
Cleaned!

And you are good to go…
PS: Your keyboard will thank you for that!