Ubuntu – What do these commands from a shell script do

bashcommand linescripts

I'm just starting to learn bash. I have the following script, and I would like to know what does the following commands do in order to start to understand a little bit this world.

if [ ! -w "." ]
then
echo "You need write permission in the directory"
exit 1
fi

firefoxGeditOpen=ps -d | grep -ic -e firefox -e gedit
if [[firefoxGeditOpen>0]]
then
echo "Firefox and Gedit must be closed to let the script work"
exit 1
fi

while(true)
do
firefox &
firefoxPid=$!
gedit &
geditPid=$!
echo "Firefox PID $firefoxPid Gedit PID $geditPid">>result.txt
wait
echo "You have closed all the processes. They will be re-opened">>result.txt
done

Thanks in advance!

Best Answer

As I mentioned in my comment there are some vital pieces missing here and these commands together don't quite make sense, but I will go over them.

  1. if [ ! -w "." ]: . represents the current directory. -w tests if it is writeable. ! negates the test (so the statement returns true if the directory is not writeable vs the other way around).

  2. ps -d | grep -ic -e firefox -e gedit: ps -d prints all processes minus session starters. grep searches the piped output from ps for patterns (which we'll get to in a minute). -i makes the search case insensitive. -c outputs a count of the matches instead of the actual matches. -e takes the search expressions. In this case firefox and gedit. So if neither FF nor gedit is running the command will output 0. If one of them is running it will output 1. If both are running it will output 2.

  3. firefox &: Start firefox. & forces the process into the background.

  4. firefoxPid=$!: In a bash shell script $! holds the job number of the last background command. firefoxPid is a variable. So what's happening here is the job number of the last background command (which happens to be firefox's) is stored to a variable named firefoxPid.