1 minute read

A curated list of tips, tricks and resources.

Tips and Tricks

Get arguments in bash alias

Alias to search for a abbreviation in wikipedia:

alias wga="bash -c '\
 curl -s https://en.wikipedia.org/wiki/List_of_abbreviations_in_oil_and_gas_exploration_and_production \
 | egrep -o \">\$0 .*<\" ' "

Sets story number in your .gitmessage file, so that you don’t have to do it every time you commit

alias start_story='bash -c '\''printf "%s" "$0"\
 > $(git rev-parse --show-toplevel)/.git/.gitmessage'\' 

Replace multiple lines in a file

Alias to replace multiple line in a ssh config file:

alias scu="bash -c \"cat ~/.ssh/config | tr '\\n' '\\r' | sed -e 's/Host test_machine\r    HostName [a-zA-Z0-9]*/Host test_machine\r    HostName '\"\\\$0\"'/'  | tr '\\r' '\\n' | tee ~/.ssh/config \""

Example ~/.ssh/config file:

Host test_machine
    HostName myhost123
    IdentityFile ~/.ssh/vscode_remote_ssh
    User ec2-user

Run command: scu myhost345

output:

Host test_machine
    HostName myhost345
    IdentityFile ~/.ssh/vscode_remote_ssh
    User ec2-user

Download a single file from a repo

Using ssh:

git archive --remote=ssh://git@code.atwork.com/my/my-scripts-repo.git HEAD tool.sh | tar –xv 

Using https, go to raw file view and get the url of the file to download:

wget -O- https://raw.githubusercontent.com/Ritesh-Yadav/Ritesh-Yadav.github.io/master/assets/scripts/install_recipe_reader.sh

Pull all git repositories

Following command pull down all the repository available in a folder:

ls -R -d */.git \
| sed 's/\/.git//' \
| xargs -I% sh -c 'echo  \"\033[0;32m-- Project: % --\033[0m\"; git -C % pull -r --autostash --all'

Static analysis of shell scripts

Use shellcheck to perform static analysis of your shell scripts. This can be integrated in lots of IDEs as well.

Testing bash scripts

BATS is a good testing framework if you are looking for writing tests for your bash scripts or even trying to test things using bash.

Self commenting script

At times, I want my scripts to self comment when I am performing some tasks and don’t want to rerun which were already successful.

sed -i.bkp "<starting_line_number>, $(( LINENO + 1 )) s/^/#/" <my_script_name>.sh
echo -e "Please press any key to continue..." && read -r -n 1 -s

example: sed -i.bkp "2, $(( LINENO + 1 )) s/^/#/" test.sh

Resources

Leave a Comment