Skip to content

Instantly share code, notes, and snippets.

@valosekj
Last active October 17, 2021 11:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valosekj/1dc705ae1fbed7afc0eee710ce081c43 to your computer and use it in GitHub Desktop.
Save valosekj/1dc705ae1fbed7afc0eee710ce081c43 to your computer and use it in GitHub Desktop.
Useful shell commands #blog

Useful shell commands

This gist contains several useful shell commands which I use frequently during my work.

$0 - Get current shell

$ echo $0
zsh

$? - Get exit status of last executed command

$ ls existing_file.txt        # This file exists, expected exit status is 0
$ echo $?
0

$ ls not_existing_file.txt    # This file does not exist, expected exit status is 2
$ echo $?     
2

$@ - Pass all input arguments received by script into function

$ some_function $@

$# - Count number of input arguments passed into function

$ some_function(){echo $1; echo $2; echo $#}      # define some function
$ some_function One Two                           # call function with two input arguments
One
Two
2

$! - Get PID of the last program ran in the background in your shell

$ fsleyes &       # run some program in the background
$ echo $!
92377

$$ - Get PID of the currently ran script

#!/bin/bash

echo "PID of this script is $$"

Get name of the shell script using string manupulation

# Note - ${0##*/} does not work, if bash script is run with source -> use $BASH_SOURCE
if [[ $SHELL =~ "bash" ]]; then
  script_name=${BASH_SOURCE[0]##*/}
elif [[ $SHELL =~ "zsh" ]]; then
  script_name=${0##*/}
fi

Get path of the shell script for different shells (bash, zsh)

if [[ ${SHELL} == "/bin/bash" ]];then
    script_path=$(dirname $(realpath -s "$0"))
elif [[ ${SHELL} == "/bin/zsh" ]];then
    script_path=$(dirname $(readlink "$0"))
fi

whoami - Get current user

$ whoami
some_user

hostname - Get current machine/computer name

$ hostname
some_hostname

uname - Get operating system name (Linux or Darwin (=MacOs))

$ uname                                                           
Linux

date - Get current date and format it

$ current_date=$(date +'%m-%d-%Y')
$ echo $current_date
05-05-2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment