Skip to content

Instantly share code, notes, and snippets.

@honey-speaks-tech
Last active May 5, 2021 13:11
Show Gist options
  • Save honey-speaks-tech/d8086ed9d8b098054da5aea9f77b3fcb to your computer and use it in GitHub Desktop.
Save honey-speaks-tech/d8086ed9d8b098054da5aea9f77b3fcb to your computer and use it in GitHub Desktop.
Shell script resources

Useful commands

pushd / popd

  • Change the current directory/folder and store the previous folder/path for use by the popd command.

Example

[user@server /usr/ports] $ pushd /etc
/etc /usr/ports
[user@server /etc] $ popd
/usr/ports
[user@server /usr/ports] $

dirname $0

  • Quick way to retrieve the path of the bash script that is being executed.

Example 1

#!/bin/bash
DIRECTORY=$(cd `dirname $0` && pwd)
echo $DIRECTORY

Example 2

#!/bin/bash
 
echo $0
 
full_path=$(realpath $0)
echo $full_path
 
dir_path=$(dirname $full_path)
echo $dir_path
 
examples=$(dirname $dir_path )
echo $examples
 
data_dir="$examples/data"
echo "DATA: $data_dir"

Output

./examples/shell/relative.sh
/home/gabor/work/code-maven.com/examples/shell/relative.sh
/home/gabor/work/code-maven.com/examples/shell
/home/gabor/work/code-maven.com/examples
DATA: /home/gabor/work/code-maven.com/examples/data

$#

  • tells the number of input arguments the script was passed.

Example 1

if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
fi

Example 2

if [ -z "$1" ]
  then
    echo "No argument supplied"
fi
  • In this example, it is not safe to use "$1" check, if it is not sure there is always an additional argument.
  • Better reference the argument, if we are sure if such argument exists. In all other cases, check the count of arguments using $# and if it is greater than zero, reference the other arguments.

command

  • POSIX compatible way of checking if a command exists or not.

Example 1

if ! command -v COMMAND &> /dev/null
then
    echo "COMMAND could not be found"
    exit
fi

history

  • command to retrieve all typed commands in bash terminal

which

  • which looks for an executable file by searching for it in the directories in the PATH environmental variable.

strace


shell

  • in GNU makefile
  • $(shell command)
  • The shell function accepts a single argument that is expanded (like all arguments) and passed to a subshell for execution. The standard output of the command is then read and returned as the value of the function. Sequences of newlines in the output are collapsed to a single space. Any trailing newline is deleted. The standard error is not returned, nor is any program exit status.

find

  • count files recursively using find
  • find -type f | wc -l

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment