Exit Shell script with error if any command fails

 

 

I wrote a Bash script today to automate my code review process and I noticed that even when certain commands in the workflow fail, the script still executes the remaining commands.

 

For example, let's say I have two commands that run synchronously:

 

git merge origin/dev git tag <new-tag>

 

In this case, if the `git merge` command fails due to some reason, it will still create a new tag, which is not my intended workflow.

 

To avoid this, if any of the commands returns a non-zero exit status, the script should break and exit. This can be achieved in Bash by using the `-e` option.

 

Add the following at the very top of your script (below the shebang line):

 

#!/bin/bash set -e

 

This will enable the `-e` option for the entire script.

If you only want to enable this option for specific commands, you can prefix them with `set -e`, like this:

 

set -e git push

 

This will cause the script to exit if the `git push` command fails.

 

Mac OS List directory in tree view using find command.

In mac (also in a Linux systems) you will have to install an additonal package called `tree` to display the content of folder in a tree view. 

 

 

 

But what if you are like me; someone who doesn't like to install additional packages just for a simple task? Well, you are at the right place then. 

 

Here is a nice command to get that done for you. Just run the following. 

 

 find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g' 


That's just it. You should see a nice tree output as shown in the above screenshot :) 

 

You could also convert this to a shell function, or an alias with a parameter to run this easily in the future.

 

Leave a comment if it helped you.


Clear scroll back buffer in zsh




In bash you can use ctrl + L to clear the scroll back in the terminal. However in zsh, it doesn't work. So here is a workaround. You can use a control sequence to clear it, and set an alias for that. 

 

Open your  .zshrc file in the editor.

$ vim ~/.zshrc

And add this to the file.

alias cls='printf "\ec\e[3J"'

Save and reload the terminal: or

    $ source ~/.zshrc

 

Now when you run the command 'cls', it should clear your terminal with its scroll back buffer. Hope it helps.