Skip to content

Instantly share code, notes, and snippets.

@savishy
Last active February 14, 2021 04:10
Show Gist options
  • Save savishy/9023f973db62462fa521 to your computer and use it in GitHub Desktop.
Save savishy/9023f973db62462fa521 to your computer and use it in GitHub Desktop.
Bash / Shell Tips and Tricks

execute command as another user

sudo -u <user> bash -c "<command to execute>"

list all users in system

cut -d: -f1 /etc/passwd

find out what group a user belongs to

getent group | grep name_of_user

list file-sizes in a folder, and sort the output by size

Note: this uses du which can get slow.

du -sh * | sort -h

A faster way to find file sizes

references: http://robert.penz.name/622/ncdu-is-better-than-calling-du-hs-multiple-times/ Requires the package ncdu.

ncdu -xq <dir name>

read output of a command line by line

From http://stackoverflow.com/a/2860103/682912

git log | while read x; do 
  # do something on $x
done

get dirname and pathname for a file path

From http://stackoverflow.com/a/6121114/682912

VAR=/home/me/mydir/file.c
DIR=$(dirname "${VAR}")
echo "${DIR}"
# /home/me/mydir
basename "${VAR}"
file.c

check if a command exists, bail otherwise

command -v foo >/dev/null 2>&1 || { echo "I require foo but it's not installed.  Aborting." >&2; exit 1; }

resize a PDF to a lower size on Linux

(This requires Ghostscript 'gs') http://askubuntu.com/a/256449

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf

check if a variable is set

source: http://stackoverflow.com/a/13864829/682912

if [[ -z $VAR ]]; then 
  echo "variable NOT set"
fi

condition: string $foo contains string $bar

if [[ "$foo" =~ "$bar" ]]; then
  echo $foo contains $bar
fi

OpenSSL Random password

openssl rand -base64 16 |  md5 |head -c16;echo
apg -a 1 -n 4 -m 8 -x 12 -s -d

Parse Commandline Arguments in Bash

From http://stackoverflow.com/a/14203146/682912

while getopts "h?vf:" opt; do
    case "$opt" in
    h|\?)
        show_help
        exit 0
        ;;
    v)  verbose=1
        ;;
    f)  output_file=$OPTARG
        ;;
    esac
done

Speed Test over command-line

Reference: sivel/speedtest-cli

wget -O speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py
chmod +x speedtest-cli
./speedtest-cli

Variable names from other variables

Reference

Example:

for var_name in AWS_ACCESS_KEY AWS_SECRET_KEY; do
# use the value of $AWS_ACCESS_KEY, $AWS_SECRET_KEY etc

echo "${!var_name}"

done

Make Ctrl+Arrow keys move one word left or right instead of printing random characters in bash.

ref

Edit the ~/.inputrc file.

"\e[1;5C": forward-word   # ctrl + right
"\e[1;5D": backward-word  # ctrl + left 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment