Skip to content

Instantly share code, notes, and snippets.

@arvindkgs
Last active September 5, 2021 12:44
Show Gist options
  • Save arvindkgs/820b10515690d9b3096226f5e4aea6f4 to your computer and use it in GitHub Desktop.
Save arvindkgs/820b10515690d9b3096226f5e4aea6f4 to your computer and use it in GitHub Desktop.
[Unix] Unix tools

File

Print from start_lineno - end_lineno

sed -n start_lineno,end_linenop file Ex: sed -n 5,10p file

Run in parallel

To run 10 processes in parallel xargs -P10
Ex: Run git pull on all folders in current directory:
ls | xargs -P10 -I{} git -C {} pull

  1. To quickly jump to important folders in your terminal, bookmark them as
    ln -s path/to/project ~/.bookmarks/@project
    then to navigate to project folder - goto @project

    But before you can do that do below -

    1. create directory ~/.bookmarks
    2. Add below to .bashrc
    if [ -d "$HOME/.bookmarks" ]; then
        export CDPATH=".:$HOME/.bookmarks:/"
        alias goto="cd -P"
        _goto()
        {
    	    local IFS=$'\n'
    	    COMPREPLY=( $( compgen -W "$(/bin/ls ~/.bookmarks)" -- ${COMP_WORDS[COMP_CWORD]}))
        } && complete -F _goto goto
    fi
    
  2. To run a script that has dependencies on other scripts from any location, add - script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" command gets the script's source file pathname, strips it to just the path portion, cds to that path, then uses pwd to return the (effectively) full path of the script. This is assigned to script_dir. After all of that, the context is unwound so you end up back in the directory you started at but with an environment variable script_dir containing the script's path. Now script_dir can be used as follows - source "${script_dir}/informal_module.sh" (Here informal_module.sh is assumed to be in same dir as current script) More here - https://advancedweb.hu/unit-testing-bash-scripts/ and https://stackoverflow.com/questions/39340169/dir-cd-dirname-bash-source0-pwd-how-does-that-work

  3. Use Bash Strict Mode

#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

Adding above to your scripts causes bash to behave in a way that makes following classes of subtle bugs impossible -

  • immediately exit if any command has a non-zero exit status
  • a reference to any variable you haven't previously defined is an error
  • errors in a pipeline from being masked.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment