Latest commit

History

189 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Commands example

This is a repository with a collection of useful commands, scripts and examples for easy copy -> paste

Table of contents

Linux

Examples

  • Clear memory cache
sync &&echo 3 | sudo tee /proc/sys/vm/drop_caches
  • Create a self-signed SSL key and certificate
mkdir -p certs/my_com
openssl req -nodes -x509 -newkey rsa:4096 -keyout certs/my_com/my_com.key -out certs/my_com/my_com.crt -days 356 -subj "/C=US/ST=California/L=SantaClara/O=IT/CN=localhost"
  • Create binary files with random content
# Just one file (1mb)
dd if=/dev/urandom of=file bs=1024 count=1024
# Create 10 files of size ~10MBforain {0..9};do \
echo${a}; \
dd if=/dev/urandom of=file.${a} bs=10240 count=1024; \
done
  • Test connection to remote host:port (check port being opened without using netcat or other tools)
# Check if port 8080 is open on remote
bash -c "</dev/tcp/remote/8080"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8080 on host 'remote' is open"
  • Suppress Terminated message from the kill on a background process by waiting for it with wait and directing the stderr output to /dev/null. This is from in this stackoverflow answer.
# Call the kill commandkill${PID}wait$!2>/dev/null
  • curl variables
    The curl command has the ability to provide a lot of information about the transfer. See curl man page.
    Search for --write-out.
    See all supported variables in curl.format.txt
# Example for getting http response code (variable http_code)
curl -o /dev/null -s --write-out '%{http_code}' https://curl.haxx.se
# Example for one-liner printout of several connection time parameters
curl -w "\ndnslookup: %{time_namelookup} \nconnect: %{time_connect} \nappconnect: %{time_appconnect} \npretransfer: %{time_pretransfer} \nredirect: %{time_redirect} \nstarttransfer: %{time_starttransfer} \n---------\ntotal: %{time_total} \nsize: %{size_download}\n" \
-so /dev/null https://curl.haxx.se
# Example for printing all variables and their values by using an external file with the format
curl -o /dev/null -s --write-out '@files/curl.format.txt' https://curl.haxx.se
  • Single binary curl
# Get the archive, extract (notice the xjf parameter to tar) and copy.
wget -O curl.tar.bz2 http://www.magicermine.com/demos/curl/curl/curl-7.30.0.ermine.tar.bz2 && \
tar xjf curl.tar.bz2 && \
cp curl-7.30.0.ermine/curl.ermine curl && \
./curl --help
# tcpdump
curl -O https://raw.githubusercontent.com/yunchih/static-binaries/master/tcpdump
  • Single static binary vi
# vi (vim)
curl -OL https://eldada.jfrog.io/artifactory/tools/x86_64/vi.tar.gz
# jq
curl -OL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
  • Get http code using wget (without curl)
    In cases where curl is not available, use wget to get the http code returned from an HTTP endpoint
wget --spider -S -T 2 www.jfrog.org 2>&1| grep "^ HTTP/"| awk '{print $2}'| tail -1
  • Poor man's top shell scripts (in Linux only!). Good for when top is not installed
    Get CPU and memory usage by processes on the current host. Also useful in Linux based Docker containers

  • Process info (in Linux only!)
    To get process info using its PID or search string: Command line, environment variables. Use procInfo.sh.

  • Add file to WAR file addFileToWar.sh

The proc directory

The /proc file system has all the information about the running processes. See full description in the proc man page.

  • Get current processes running (a simple alternative to ps in case it's missing)
forain$(ls -d /proc/*/);doif [[ -f$a/exe ]];then ls -l ${a}exe;fi;done
# Assume PID is the process ID you are looking at
cat /proc/${PID}/cmdline | tr '\0'''# or
cat /proc/${PID}/cmdline | sed -z 's/$/ /g'
  • Get a process environment variables (see usage in procInfo.sh)
# Assume PID is the process ID you are looking at
cat /proc/${PID}/environ | tr '\0''\n'# or
cat /proc/${PID}/environ | sed -z 's/$/\n/g'
  • Get load average from disk instead of command
cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}'
  • Get top 10 processes IDs and names sorted with highest time waiting for disk IO (Aggregated block I/O delays, measured in clock ticks)
cut -d"" -f 1,2,42 /proc/[0-9]*/stat | sort -n -k 3 | tail -10

Screen

# Start a new session with session name
screen -S <session_name># List running screens
screen -ls
# Attach to a running session
screen -x
# Attach to a running session with name
screen -r <session_name># Detach a running session
screen -d <session_name>
  • Screen commands are prefixed by an escape key, by default Ctrl-a (that's Control-a, sometimes written ^a). To send a literal Ctrl-a to the programs in screen, use Ctrl-a a. This is useful when when working with screen within screen. For example Ctrl-a a n will move screen to a new window on the screen within screen.
DescriptionCommand
Exit and close sessionCtrl-d or exit
Detach current sessionCtrl-a d
Detach and logout (quick exit)Ctrl-a D D
Kill current windowCtrl-a k
Exit screenCtrl-a : quit or exit all of the programs in screen
Force-exit screenCtrl-a C-\ (not recommended)
  • Help
DescriptionCommand
See helpCtrl-a ? (Lists keybindings)

Sysbench

Sysbench is a mutli-purpose benchmark that features tests for CPU, memory, I/O, and even database performance testing.
See full content for this section in linuxconfig.org's how to benchmark your linux system.

  • Installation (Debian/Ubuntu)
sudo apt install sysbench
  • CPU benchmark
sysbench --test=cpu run
  • Memory benchmark
sysbench --test=memory run
  • I/O benchmark
sysbench --test=fileio --file-test-mode=seqwr run

Apache Bench

From the Apache HTTP server benchmarking tool page: "ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server."

# A simple benchmarking of a web server. Running 100 requests with up to 10 concurrent requests
ab -n 100 -c 10 http://www.jfrog.com/

Load generator

A simple createLoad.sh script to create disk IO and CPU load in the current environment. This script just creates and deletes files in a temp directory which strains the CPU and disk IO.
WARNING: Running this script with many threads can bring a system to a halt or even crash it. USE WITH CARE!

./createLoad.sh --threads 10

Git

  • Rebasing a branch on master
# Update local copy of master
git checkout master
git pull
# Rebase the branch on the updated master
git checkout my-branch
git rebase master
# Rebase and squash
git rebase master -i
# If problems are found, follow on screen instructions to resolve and complete the rebase.
  • Resetting a fork with upstream. WARNING: This will override any local changes in your fork!
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master git push origin master --force 
  • Add Signed-off-by line by the committer at the end of the commit log message.
git commit -s -m "Your commit message"

Java

Some useful commands for debugging a java process

# Go to the java/bin directorycd${JAVA_HOME}/bin
# Get your java process id
PID=$(ps -ef | grep java | grep -v grep | awk '{print $2}')# Get JVM native memory usage# For this, you need your java process to run with the the -XX:NativeMemoryTracking=summary parameter
./jcmd ${PID} VM.native_memory summary
# Get all JVM info
./jinfo ${PID}# Get JVM flags for a java process
./jinfo -flags ${PID}# Get JVM heap info 
./jcmd ${PID} GC.heap_info
# Get JVM Metaspace info
./jcmd ${PID} VM.metaspace
# Trigger a full GC
./jcmd ${PID} GC.run
# Java heap memory histogram
./jmap -histo ${PID}

Docker

  • Allow a user to run docker commands without sudo
sudo usermod -aG docker user
# IMPORTANT: Log out and back in after this change!
  • See what Docker is using
docker system df
  • Prune Docker unused resources
# Prune system
docker system prune
# Remove all unused Docker images
docker system prune -a
# Prune only parts
docker image/container/volume/network prune
  • Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
  • Quit an interactive session without closing it:
# Ctrl + p + q (order is important)
  • Attach back to it
docker attach <container-id>
  • Save a Docker image to be loaded in another computer
# Save
docker save -o ~/the.img the-image:tag
# Load into another Docker engine
docker load -i ~/the.img
  • Connect to Docker VM on Mac
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
# Ctrl +A +D to exit
  • Adding an insecure registry in Rancher Desktop

    1. Connect to the Rancher Desktop VM on Mac

      LIMA_HOME="${HOME}/Library/Application Support/rancher-desktop/lima""/Applications/Rancher Desktop.app/Contents/Resources/resources/darwin/lima/bin/limactl" shell 0
    2. Once in the VM

      vi /etc/docker/daemon.json
    3. Edit the file with the insecure registries you want

      {
      "features": {
      "containerd-snapshotter": false
      },
      "insecure-registries": [
      "host.docker.internal",
      "dummy.registry"
      ]
      }
    4. Restart the Docker daemon

      sudo service docker restart
  • Remove none images (usually leftover failed docker builds)

docker images | grep none | awk '{print $3}'| xargs docker rmi
  • Using dive to analyse a Docker image
# Must pull the image before analysis
docker pull redis:latest
# Run using dive Docker image
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest redis:latest
  • Adding health checks for containers that check tcp port being opened without using netcat or other tools in your image
# Check if port 8081 is open
bash -c "</dev/tcp/localhost/8081"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8081 on localhost is open"

Tools

A collection of useful Docker tools

  • A simple terminal UI for Docker and docker-compose: lazydocker
  • A web based UI for local and remote Docker: Portainer
  • Analyze a Docker image with dive

My Dockerfiles

A few Dockerfiles I use in my work

# For a local build
docker build -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 --push .
# For a local build
docker build -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 --push .

Artifactory

See Artifactory related scripts and examples in artifactory

Matrix

A command line effect of the Matrix (the movie) text

whiletrue;doecho$LINES$COLUMNS$((RANDOM %$COLUMNS))$(printf "\U$((RANDOM %500))"); sleep 0.04;done| awk '{a[$3]=0; for (x in a){o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,$4; printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x],x,$4; if (a[x]>=$1){a[x]=0;}}}'

Contribute

Contributing is more than welcome with a pull request

About

A collection of useful commands with various tools

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

189 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Commands example

This is a repository with a collection of useful commands, scripts and examples for easy copy -> paste

Table of contents

Linux

Examples

  • Clear memory cache
sync &&echo 3 | sudo tee /proc/sys/vm/drop_caches
  • Create a self-signed SSL key and certificate
mkdir -p certs/my_com
openssl req -nodes -x509 -newkey rsa:4096 -keyout certs/my_com/my_com.key -out certs/my_com/my_com.crt -days 356 -subj "/C=US/ST=California/L=SantaClara/O=IT/CN=localhost"
  • Create binary files with random content
# Just one file (1mb)
dd if=/dev/urandom of=file bs=1024 count=1024
# Create 10 files of size ~10MBforain {0..9};do \
echo${a}; \
dd if=/dev/urandom of=file.${a} bs=10240 count=1024; \
done
  • Test connection to remote host:port (check port being opened without using netcat or other tools)
# Check if port 8080 is open on remote
bash -c "</dev/tcp/remote/8080"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8080 on host 'remote' is open"
  • Suppress Terminated message from the kill on a background process by waiting for it with wait and directing the stderr output to /dev/null. This is from in this stackoverflow answer.
# Call the kill commandkill${PID}wait$!2>/dev/null
  • curl variables
    The curl command has the ability to provide a lot of information about the transfer. See curl man page.
    Search for --write-out.
    See all supported variables in curl.format.txt
# Example for getting http response code (variable http_code)
curl -o /dev/null -s --write-out '%{http_code}' https://curl.haxx.se
# Example for one-liner printout of several connection time parameters
curl -w "\ndnslookup: %{time_namelookup} \nconnect: %{time_connect} \nappconnect: %{time_appconnect} \npretransfer: %{time_pretransfer} \nredirect: %{time_redirect} \nstarttransfer: %{time_starttransfer} \n---------\ntotal: %{time_total} \nsize: %{size_download}\n" \
-so /dev/null https://curl.haxx.se
# Example for printing all variables and their values by using an external file with the format
curl -o /dev/null -s --write-out '@files/curl.format.txt' https://curl.haxx.se
  • Single binary curl
# Get the archive, extract (notice the xjf parameter to tar) and copy.
wget -O curl.tar.bz2 http://www.magicermine.com/demos/curl/curl/curl-7.30.0.ermine.tar.bz2 && \
tar xjf curl.tar.bz2 && \
cp curl-7.30.0.ermine/curl.ermine curl && \
./curl --help
# tcpdump
curl -O https://raw.githubusercontent.com/yunchih/static-binaries/master/tcpdump
  • Single static binary vi
# vi (vim)
curl -OL https://eldada.jfrog.io/artifactory/tools/x86_64/vi.tar.gz
# jq
curl -OL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
  • Get http code using wget (without curl)
    In cases where curl is not available, use wget to get the http code returned from an HTTP endpoint
wget --spider -S -T 2 www.jfrog.org 2>&1| grep "^ HTTP/"| awk '{print $2}'| tail -1
  • Poor man's top shell scripts (in Linux only!). Good for when top is not installed
    Get CPU and memory usage by processes on the current host. Also useful in Linux based Docker containers

  • Process info (in Linux only!)
    To get process info using its PID or search string: Command line, environment variables. Use procInfo.sh.

  • Add file to WAR file addFileToWar.sh

The proc directory

The /proc file system has all the information about the running processes. See full description in the proc man page.

  • Get current processes running (a simple alternative to ps in case it's missing)
forain$(ls -d /proc/*/);doif [[ -f$a/exe ]];then ls -l ${a}exe;fi;done
# Assume PID is the process ID you are looking at
cat /proc/${PID}/cmdline | tr '\0'''# or
cat /proc/${PID}/cmdline | sed -z 's/$/ /g'
  • Get a process environment variables (see usage in procInfo.sh)
# Assume PID is the process ID you are looking at
cat /proc/${PID}/environ | tr '\0''\n'# or
cat /proc/${PID}/environ | sed -z 's/$/\n/g'
  • Get load average from disk instead of command
cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}'
  • Get top 10 processes IDs and names sorted with highest time waiting for disk IO (Aggregated block I/O delays, measured in clock ticks)
cut -d"" -f 1,2,42 /proc/[0-9]*/stat | sort -n -k 3 | tail -10

Screen

# Start a new session with session name
screen -S <session_name># List running screens
screen -ls
# Attach to a running session
screen -x
# Attach to a running session with name
screen -r <session_name># Detach a running session
screen -d <session_name>
  • Screen commands are prefixed by an escape key, by default Ctrl-a (that's Control-a, sometimes written ^a). To send a literal Ctrl-a to the programs in screen, use Ctrl-a a. This is useful when when working with screen within screen. For example Ctrl-a a n will move screen to a new window on the screen within screen.
DescriptionCommand
Exit and close sessionCtrl-d or exit
Detach current sessionCtrl-a d
Detach and logout (quick exit)Ctrl-a D D
Kill current windowCtrl-a k
Exit screenCtrl-a : quit or exit all of the programs in screen
Force-exit screenCtrl-a C-\ (not recommended)
  • Help
DescriptionCommand
See helpCtrl-a ? (Lists keybindings)

Sysbench

Sysbench is a mutli-purpose benchmark that features tests for CPU, memory, I/O, and even database performance testing.
See full content for this section in linuxconfig.org's how to benchmark your linux system.

  • Installation (Debian/Ubuntu)
sudo apt install sysbench
  • CPU benchmark
sysbench --test=cpu run
  • Memory benchmark
sysbench --test=memory run
  • I/O benchmark
sysbench --test=fileio --file-test-mode=seqwr run

Apache Bench

From the Apache HTTP server benchmarking tool page: "ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server."

# A simple benchmarking of a web server. Running 100 requests with up to 10 concurrent requests
ab -n 100 -c 10 http://www.jfrog.com/

Load generator

A simple createLoad.sh script to create disk IO and CPU load in the current environment. This script just creates and deletes files in a temp directory which strains the CPU and disk IO.
WARNING: Running this script with many threads can bring a system to a halt or even crash it. USE WITH CARE!

./createLoad.sh --threads 10

Git

  • Rebasing a branch on master
# Update local copy of master
git checkout master
git pull
# Rebase the branch on the updated master
git checkout my-branch
git rebase master
# Rebase and squash
git rebase master -i
# If problems are found, follow on screen instructions to resolve and complete the rebase.
  • Resetting a fork with upstream. WARNING: This will override any local changes in your fork!
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master git push origin master --force 
  • Add Signed-off-by line by the committer at the end of the commit log message.
git commit -s -m "Your commit message"

Java

Some useful commands for debugging a java process

# Go to the java/bin directorycd${JAVA_HOME}/bin
# Get your java process id
PID=$(ps -ef | grep java | grep -v grep | awk '{print $2}')# Get JVM native memory usage# For this, you need your java process to run with the the -XX:NativeMemoryTracking=summary parameter
./jcmd ${PID} VM.native_memory summary
# Get all JVM info
./jinfo ${PID}# Get JVM flags for a java process
./jinfo -flags ${PID}# Get JVM heap info 
./jcmd ${PID} GC.heap_info
# Get JVM Metaspace info
./jcmd ${PID} VM.metaspace
# Trigger a full GC
./jcmd ${PID} GC.run
# Java heap memory histogram
./jmap -histo ${PID}

Docker

  • Allow a user to run docker commands without sudo
sudo usermod -aG docker user
# IMPORTANT: Log out and back in after this change!
  • See what Docker is using
docker system df
  • Prune Docker unused resources
# Prune system
docker system prune
# Remove all unused Docker images
docker system prune -a
# Prune only parts
docker image/container/volume/network prune
  • Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
  • Quit an interactive session without closing it:
# Ctrl + p + q (order is important)
  • Attach back to it
docker attach <container-id>
  • Save a Docker image to be loaded in another computer
# Save
docker save -o ~/the.img the-image:tag
# Load into another Docker engine
docker load -i ~/the.img
  • Connect to Docker VM on Mac
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
# Ctrl +A +D to exit
  • Adding an insecure registry in Rancher Desktop

    1. Connect to the Rancher Desktop VM on Mac

      LIMA_HOME="${HOME}/Library/Application Support/rancher-desktop/lima""/Applications/Rancher Desktop.app/Contents/Resources/resources/darwin/lima/bin/limactl" shell 0
    2. Once in the VM

      vi /etc/docker/daemon.json
    3. Edit the file with the insecure registries you want

      {
      "features": {
      "containerd-snapshotter": false
      },
      "insecure-registries": [
      "host.docker.internal",
      "dummy.registry"
      ]
      }
    4. Restart the Docker daemon

      sudo service docker restart
  • Remove none images (usually leftover failed docker builds)

docker images | grep none | awk '{print $3}'| xargs docker rmi
  • Using dive to analyse a Docker image
# Must pull the image before analysis
docker pull redis:latest
# Run using dive Docker image
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest redis:latest
  • Adding health checks for containers that check tcp port being opened without using netcat or other tools in your image
# Check if port 8081 is open
bash -c "</dev/tcp/localhost/8081"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8081 on localhost is open"

Tools

A collection of useful Docker tools

  • A simple terminal UI for Docker and docker-compose: lazydocker
  • A web based UI for local and remote Docker: Portainer
  • Analyze a Docker image with dive

My Dockerfiles

A few Dockerfiles I use in my work

# For a local build
docker build -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 --push .
# For a local build
docker build -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 --push .

Artifactory

See Artifactory related scripts and examples in artifactory

Matrix

A command line effect of the Matrix (the movie) text

whiletrue;doecho$LINES$COLUMNS$((RANDOM %$COLUMNS))$(printf "\U$((RANDOM %500))"); sleep 0.04;done| awk '{a[$3]=0; for (x in a){o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,$4; printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x],x,$4; if (a[x]>=$1){a[x]=0;}}}'

Contribute

Contributing is more than welcome with a pull request

About

A collection of useful commands with various tools

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

189 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Commands example

This is a repository with a collection of useful commands, scripts and examples for easy copy -> paste

Table of contents

Linux

Examples

  • Clear memory cache
sync &&echo 3 | sudo tee /proc/sys/vm/drop_caches
  • Create a self-signed SSL key and certificate
mkdir -p certs/my_com
openssl req -nodes -x509 -newkey rsa:4096 -keyout certs/my_com/my_com.key -out certs/my_com/my_com.crt -days 356 -subj "/C=US/ST=California/L=SantaClara/O=IT/CN=localhost"
  • Create binary files with random content
# Just one file (1mb)
dd if=/dev/urandom of=file bs=1024 count=1024
# Create 10 files of size ~10MBforain {0..9};do \
echo${a}; \
dd if=/dev/urandom of=file.${a} bs=10240 count=1024; \
done
  • Test connection to remote host:port (check port being opened without using netcat or other tools)
# Check if port 8080 is open on remote
bash -c "</dev/tcp/remote/8080"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8080 on host 'remote' is open"
  • Suppress Terminated message from the kill on a background process by waiting for it with wait and directing the stderr output to /dev/null. This is from in this stackoverflow answer.
# Call the kill commandkill${PID}wait$!2>/dev/null
  • curl variables
    The curl command has the ability to provide a lot of information about the transfer. See curl man page.
    Search for --write-out.
    See all supported variables in curl.format.txt
# Example for getting http response code (variable http_code)
curl -o /dev/null -s --write-out '%{http_code}' https://curl.haxx.se
# Example for one-liner printout of several connection time parameters
curl -w "\ndnslookup: %{time_namelookup} \nconnect: %{time_connect} \nappconnect: %{time_appconnect} \npretransfer: %{time_pretransfer} \nredirect: %{time_redirect} \nstarttransfer: %{time_starttransfer} \n---------\ntotal: %{time_total} \nsize: %{size_download}\n" \
-so /dev/null https://curl.haxx.se
# Example for printing all variables and their values by using an external file with the format
curl -o /dev/null -s --write-out '@files/curl.format.txt' https://curl.haxx.se
  • Single binary curl
# Get the archive, extract (notice the xjf parameter to tar) and copy.
wget -O curl.tar.bz2 http://www.magicermine.com/demos/curl/curl/curl-7.30.0.ermine.tar.bz2 && \
tar xjf curl.tar.bz2 && \
cp curl-7.30.0.ermine/curl.ermine curl && \
./curl --help
# tcpdump
curl -O https://raw.githubusercontent.com/yunchih/static-binaries/master/tcpdump
  • Single static binary vi
# vi (vim)
curl -OL https://eldada.jfrog.io/artifactory/tools/x86_64/vi.tar.gz
# jq
curl -OL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
  • Get http code using wget (without curl)
    In cases where curl is not available, use wget to get the http code returned from an HTTP endpoint
wget --spider -S -T 2 www.jfrog.org 2>&1| grep "^ HTTP/"| awk '{print $2}'| tail -1
  • Poor man's top shell scripts (in Linux only!). Good for when top is not installed
    Get CPU and memory usage by processes on the current host. Also useful in Linux based Docker containers

  • Process info (in Linux only!)
    To get process info using its PID or search string: Command line, environment variables. Use procInfo.sh.

  • Add file to WAR file addFileToWar.sh

The proc directory

The /proc file system has all the information about the running processes. See full description in the proc man page.

  • Get current processes running (a simple alternative to ps in case it's missing)
forain$(ls -d /proc/*/);doif [[ -f$a/exe ]];then ls -l ${a}exe;fi;done
# Assume PID is the process ID you are looking at
cat /proc/${PID}/cmdline | tr '\0'''# or
cat /proc/${PID}/cmdline | sed -z 's/$/ /g'
  • Get a process environment variables (see usage in procInfo.sh)
# Assume PID is the process ID you are looking at
cat /proc/${PID}/environ | tr '\0''\n'# or
cat /proc/${PID}/environ | sed -z 's/$/\n/g'
  • Get load average from disk instead of command
cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}'
  • Get top 10 processes IDs and names sorted with highest time waiting for disk IO (Aggregated block I/O delays, measured in clock ticks)
cut -d"" -f 1,2,42 /proc/[0-9]*/stat | sort -n -k 3 | tail -10

Screen

# Start a new session with session name
screen -S <session_name># List running screens
screen -ls
# Attach to a running session
screen -x
# Attach to a running session with name
screen -r <session_name># Detach a running session
screen -d <session_name>
  • Screen commands are prefixed by an escape key, by default Ctrl-a (that's Control-a, sometimes written ^a). To send a literal Ctrl-a to the programs in screen, use Ctrl-a a. This is useful when when working with screen within screen. For example Ctrl-a a n will move screen to a new window on the screen within screen.
DescriptionCommand
Exit and close sessionCtrl-d or exit
Detach current sessionCtrl-a d
Detach and logout (quick exit)Ctrl-a D D
Kill current windowCtrl-a k
Exit screenCtrl-a : quit or exit all of the programs in screen
Force-exit screenCtrl-a C-\ (not recommended)
  • Help
DescriptionCommand
See helpCtrl-a ? (Lists keybindings)

Sysbench

Sysbench is a mutli-purpose benchmark that features tests for CPU, memory, I/O, and even database performance testing.
See full content for this section in linuxconfig.org's how to benchmark your linux system.

  • Installation (Debian/Ubuntu)
sudo apt install sysbench
  • CPU benchmark
sysbench --test=cpu run
  • Memory benchmark
sysbench --test=memory run
  • I/O benchmark
sysbench --test=fileio --file-test-mode=seqwr run

Apache Bench

From the Apache HTTP server benchmarking tool page: "ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server."

# A simple benchmarking of a web server. Running 100 requests with up to 10 concurrent requests
ab -n 100 -c 10 http://www.jfrog.com/

Load generator

A simple createLoad.sh script to create disk IO and CPU load in the current environment. This script just creates and deletes files in a temp directory which strains the CPU and disk IO.
WARNING: Running this script with many threads can bring a system to a halt or even crash it. USE WITH CARE!

./createLoad.sh --threads 10

Git

  • Rebasing a branch on master
# Update local copy of master
git checkout master
git pull
# Rebase the branch on the updated master
git checkout my-branch
git rebase master
# Rebase and squash
git rebase master -i
# If problems are found, follow on screen instructions to resolve and complete the rebase.
  • Resetting a fork with upstream. WARNING: This will override any local changes in your fork!
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master git push origin master --force 
  • Add Signed-off-by line by the committer at the end of the commit log message.
git commit -s -m "Your commit message"

Java

Some useful commands for debugging a java process

# Go to the java/bin directorycd${JAVA_HOME}/bin
# Get your java process id
PID=$(ps -ef | grep java | grep -v grep | awk '{print $2}')# Get JVM native memory usage# For this, you need your java process to run with the the -XX:NativeMemoryTracking=summary parameter
./jcmd ${PID} VM.native_memory summary
# Get all JVM info
./jinfo ${PID}# Get JVM flags for a java process
./jinfo -flags ${PID}# Get JVM heap info 
./jcmd ${PID} GC.heap_info
# Get JVM Metaspace info
./jcmd ${PID} VM.metaspace
# Trigger a full GC
./jcmd ${PID} GC.run
# Java heap memory histogram
./jmap -histo ${PID}

Docker

  • Allow a user to run docker commands without sudo
sudo usermod -aG docker user
# IMPORTANT: Log out and back in after this change!
  • See what Docker is using
docker system df
  • Prune Docker unused resources
# Prune system
docker system prune
# Remove all unused Docker images
docker system prune -a
# Prune only parts
docker image/container/volume/network prune
  • Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
  • Quit an interactive session without closing it:
# Ctrl + p + q (order is important)
  • Attach back to it
docker attach <container-id>
  • Save a Docker image to be loaded in another computer
# Save
docker save -o ~/the.img the-image:tag
# Load into another Docker engine
docker load -i ~/the.img
  • Connect to Docker VM on Mac
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
# Ctrl +A +D to exit
  • Adding an insecure registry in Rancher Desktop

    1. Connect to the Rancher Desktop VM on Mac

      LIMA_HOME="${HOME}/Library/Application Support/rancher-desktop/lima""/Applications/Rancher Desktop.app/Contents/Resources/resources/darwin/lima/bin/limactl" shell 0
    2. Once in the VM

      vi /etc/docker/daemon.json
    3. Edit the file with the insecure registries you want

      {
      "features": {
      "containerd-snapshotter": false
      },
      "insecure-registries": [
      "host.docker.internal",
      "dummy.registry"
      ]
      }
    4. Restart the Docker daemon

      sudo service docker restart
  • Remove none images (usually leftover failed docker builds)

docker images | grep none | awk '{print $3}'| xargs docker rmi
  • Using dive to analyse a Docker image
# Must pull the image before analysis
docker pull redis:latest
# Run using dive Docker image
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest redis:latest
  • Adding health checks for containers that check tcp port being opened without using netcat or other tools in your image
# Check if port 8081 is open
bash -c "</dev/tcp/localhost/8081"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8081 on localhost is open"

Tools

A collection of useful Docker tools

  • A simple terminal UI for Docker and docker-compose: lazydocker
  • A web based UI for local and remote Docker: Portainer
  • Analyze a Docker image with dive

My Dockerfiles

A few Dockerfiles I use in my work

# For a local build
docker build -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 --push .
# For a local build
docker build -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 --push .

Artifactory

See Artifactory related scripts and examples in artifactory

Matrix

A command line effect of the Matrix (the movie) text

whiletrue;doecho$LINES$COLUMNS$((RANDOM %$COLUMNS))$(printf "\U$((RANDOM %500))"); sleep 0.04;done| awk '{a[$3]=0; for (x in a){o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,$4; printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x],x,$4; if (a[x]>=$1){a[x]=0;}}}'

Contribute

Contributing is more than welcome with a pull request

About

A collection of useful commands with various tools

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

189 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Commands example

This is a repository with a collection of useful commands, scripts and examples for easy copy -> paste

Table of contents

Linux

Examples

  • Clear memory cache
sync &&echo 3 | sudo tee /proc/sys/vm/drop_caches
  • Create a self-signed SSL key and certificate
mkdir -p certs/my_com
openssl req -nodes -x509 -newkey rsa:4096 -keyout certs/my_com/my_com.key -out certs/my_com/my_com.crt -days 356 -subj "/C=US/ST=California/L=SantaClara/O=IT/CN=localhost"
  • Create binary files with random content
# Just one file (1mb)
dd if=/dev/urandom of=file bs=1024 count=1024
# Create 10 files of size ~10MBforain {0..9};do \
echo${a}; \
dd if=/dev/urandom of=file.${a} bs=10240 count=1024; \
done
  • Test connection to remote host:port (check port being opened without using netcat or other tools)
# Check if port 8080 is open on remote
bash -c "</dev/tcp/remote/8080"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8080 on host 'remote' is open"
  • Suppress Terminated message from the kill on a background process by waiting for it with wait and directing the stderr output to /dev/null. This is from in this stackoverflow answer.
# Call the kill commandkill${PID}wait$!2>/dev/null
  • curl variables
    The curl command has the ability to provide a lot of information about the transfer. See curl man page.
    Search for --write-out.
    See all supported variables in curl.format.txt
# Example for getting http response code (variable http_code)
curl -o /dev/null -s --write-out '%{http_code}' https://curl.haxx.se
# Example for one-liner printout of several connection time parameters
curl -w "\ndnslookup: %{time_namelookup} \nconnect: %{time_connect} \nappconnect: %{time_appconnect} \npretransfer: %{time_pretransfer} \nredirect: %{time_redirect} \nstarttransfer: %{time_starttransfer} \n---------\ntotal: %{time_total} \nsize: %{size_download}\n" \
-so /dev/null https://curl.haxx.se
# Example for printing all variables and their values by using an external file with the format
curl -o /dev/null -s --write-out '@files/curl.format.txt' https://curl.haxx.se
  • Single binary curl
# Get the archive, extract (notice the xjf parameter to tar) and copy.
wget -O curl.tar.bz2 http://www.magicermine.com/demos/curl/curl/curl-7.30.0.ermine.tar.bz2 && \
tar xjf curl.tar.bz2 && \
cp curl-7.30.0.ermine/curl.ermine curl && \
./curl --help
# tcpdump
curl -O https://raw.githubusercontent.com/yunchih/static-binaries/master/tcpdump
  • Single static binary vi
# vi (vim)
curl -OL https://eldada.jfrog.io/artifactory/tools/x86_64/vi.tar.gz
# jq
curl -OL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
  • Get http code using wget (without curl)
    In cases where curl is not available, use wget to get the http code returned from an HTTP endpoint
wget --spider -S -T 2 www.jfrog.org 2>&1| grep "^ HTTP/"| awk '{print $2}'| tail -1
  • Poor man's top shell scripts (in Linux only!). Good for when top is not installed
    Get CPU and memory usage by processes on the current host. Also useful in Linux based Docker containers

  • Process info (in Linux only!)
    To get process info using its PID or search string: Command line, environment variables. Use procInfo.sh.

  • Add file to WAR file addFileToWar.sh

The proc directory

The /proc file system has all the information about the running processes. See full description in the proc man page.

  • Get current processes running (a simple alternative to ps in case it's missing)
forain$(ls -d /proc/*/);doif [[ -f$a/exe ]];then ls -l ${a}exe;fi;done
# Assume PID is the process ID you are looking at
cat /proc/${PID}/cmdline | tr '\0'''# or
cat /proc/${PID}/cmdline | sed -z 's/$/ /g'
  • Get a process environment variables (see usage in procInfo.sh)
# Assume PID is the process ID you are looking at
cat /proc/${PID}/environ | tr '\0''\n'# or
cat /proc/${PID}/environ | sed -z 's/$/\n/g'
  • Get load average from disk instead of command
cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}'
  • Get top 10 processes IDs and names sorted with highest time waiting for disk IO (Aggregated block I/O delays, measured in clock ticks)
cut -d"" -f 1,2,42 /proc/[0-9]*/stat | sort -n -k 3 | tail -10

Screen

# Start a new session with session name
screen -S <session_name># List running screens
screen -ls
# Attach to a running session
screen -x
# Attach to a running session with name
screen -r <session_name># Detach a running session
screen -d <session_name>
  • Screen commands are prefixed by an escape key, by default Ctrl-a (that's Control-a, sometimes written ^a). To send a literal Ctrl-a to the programs in screen, use Ctrl-a a. This is useful when when working with screen within screen. For example Ctrl-a a n will move screen to a new window on the screen within screen.
DescriptionCommand
Exit and close sessionCtrl-d or exit
Detach current sessionCtrl-a d
Detach and logout (quick exit)Ctrl-a D D
Kill current windowCtrl-a k
Exit screenCtrl-a : quit or exit all of the programs in screen
Force-exit screenCtrl-a C-\ (not recommended)
  • Help
DescriptionCommand
See helpCtrl-a ? (Lists keybindings)

Sysbench

Sysbench is a mutli-purpose benchmark that features tests for CPU, memory, I/O, and even database performance testing.
See full content for this section in linuxconfig.org's how to benchmark your linux system.

  • Installation (Debian/Ubuntu)
sudo apt install sysbench
  • CPU benchmark
sysbench --test=cpu run
  • Memory benchmark
sysbench --test=memory run
  • I/O benchmark
sysbench --test=fileio --file-test-mode=seqwr run

Apache Bench

From the Apache HTTP server benchmarking tool page: "ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server."

# A simple benchmarking of a web server. Running 100 requests with up to 10 concurrent requests
ab -n 100 -c 10 http://www.jfrog.com/

Load generator

A simple createLoad.sh script to create disk IO and CPU load in the current environment. This script just creates and deletes files in a temp directory which strains the CPU and disk IO.
WARNING: Running this script with many threads can bring a system to a halt or even crash it. USE WITH CARE!

./createLoad.sh --threads 10

Git

  • Rebasing a branch on master
# Update local copy of master
git checkout master
git pull
# Rebase the branch on the updated master
git checkout my-branch
git rebase master
# Rebase and squash
git rebase master -i
# If problems are found, follow on screen instructions to resolve and complete the rebase.
  • Resetting a fork with upstream. WARNING: This will override any local changes in your fork!
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master git push origin master --force 
  • Add Signed-off-by line by the committer at the end of the commit log message.
git commit -s -m "Your commit message"

Java

Some useful commands for debugging a java process

# Go to the java/bin directorycd${JAVA_HOME}/bin
# Get your java process id
PID=$(ps -ef | grep java | grep -v grep | awk '{print $2}')# Get JVM native memory usage# For this, you need your java process to run with the the -XX:NativeMemoryTracking=summary parameter
./jcmd ${PID} VM.native_memory summary
# Get all JVM info
./jinfo ${PID}# Get JVM flags for a java process
./jinfo -flags ${PID}# Get JVM heap info 
./jcmd ${PID} GC.heap_info
# Get JVM Metaspace info
./jcmd ${PID} VM.metaspace
# Trigger a full GC
./jcmd ${PID} GC.run
# Java heap memory histogram
./jmap -histo ${PID}

Docker

  • Allow a user to run docker commands without sudo
sudo usermod -aG docker user
# IMPORTANT: Log out and back in after this change!
  • See what Docker is using
docker system df
  • Prune Docker unused resources
# Prune system
docker system prune
# Remove all unused Docker images
docker system prune -a
# Prune only parts
docker image/container/volume/network prune
  • Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
  • Quit an interactive session without closing it:
# Ctrl + p + q (order is important)
  • Attach back to it
docker attach <container-id>
  • Save a Docker image to be loaded in another computer
# Save
docker save -o ~/the.img the-image:tag
# Load into another Docker engine
docker load -i ~/the.img
  • Connect to Docker VM on Mac
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
# Ctrl +A +D to exit
  • Adding an insecure registry in Rancher Desktop

    1. Connect to the Rancher Desktop VM on Mac

      LIMA_HOME="${HOME}/Library/Application Support/rancher-desktop/lima""/Applications/Rancher Desktop.app/Contents/Resources/resources/darwin/lima/bin/limactl" shell 0
    2. Once in the VM

      vi /etc/docker/daemon.json
    3. Edit the file with the insecure registries you want

      {
      "features": {
      "containerd-snapshotter": false
      },
      "insecure-registries": [
      "host.docker.internal",
      "dummy.registry"
      ]
      }
    4. Restart the Docker daemon

      sudo service docker restart
  • Remove none images (usually leftover failed docker builds)

docker images | grep none | awk '{print $3}'| xargs docker rmi
  • Using dive to analyse a Docker image
# Must pull the image before analysis
docker pull redis:latest
# Run using dive Docker image
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest redis:latest
  • Adding health checks for containers that check tcp port being opened without using netcat or other tools in your image
# Check if port 8081 is open
bash -c "</dev/tcp/localhost/8081"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8081 on localhost is open"

Tools

A collection of useful Docker tools

  • A simple terminal UI for Docker and docker-compose: lazydocker
  • A web based UI for local and remote Docker: Portainer
  • Analyze a Docker image with dive

My Dockerfiles

A few Dockerfiles I use in my work

# For a local build
docker build -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 --push .
# For a local build
docker build -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 --push .

Artifactory

See Artifactory related scripts and examples in artifactory

Matrix

A command line effect of the Matrix (the movie) text

whiletrue;doecho$LINES$COLUMNS$((RANDOM %$COLUMNS))$(printf "\U$((RANDOM %500))"); sleep 0.04;done| awk '{a[$3]=0; for (x in a){o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,$4; printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x],x,$4; if (a[x]>=$1){a[x]=0;}}}'

Contribute

Contributing is more than welcome with a pull request

About

A collection of useful commands with various tools

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

189 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Commands example

This is a repository with a collection of useful commands, scripts and examples for easy copy -> paste

Table of contents

Linux

Examples

  • Clear memory cache
sync &&echo 3 | sudo tee /proc/sys/vm/drop_caches
  • Create a self-signed SSL key and certificate
mkdir -p certs/my_com
openssl req -nodes -x509 -newkey rsa:4096 -keyout certs/my_com/my_com.key -out certs/my_com/my_com.crt -days 356 -subj "/C=US/ST=California/L=SantaClara/O=IT/CN=localhost"
  • Create binary files with random content
# Just one file (1mb)
dd if=/dev/urandom of=file bs=1024 count=1024
# Create 10 files of size ~10MBforain {0..9};do \
echo${a}; \
dd if=/dev/urandom of=file.${a} bs=10240 count=1024; \
done
  • Test connection to remote host:port (check port being opened without using netcat or other tools)
# Check if port 8080 is open on remote
bash -c "</dev/tcp/remote/8080"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8080 on host 'remote' is open"
  • Suppress Terminated message from the kill on a background process by waiting for it with wait and directing the stderr output to /dev/null. This is from in this stackoverflow answer.
# Call the kill commandkill${PID}wait$!2>/dev/null
  • curl variables
    The curl command has the ability to provide a lot of information about the transfer. See curl man page.
    Search for --write-out.
    See all supported variables in curl.format.txt
# Example for getting http response code (variable http_code)
curl -o /dev/null -s --write-out '%{http_code}' https://curl.haxx.se
# Example for one-liner printout of several connection time parameters
curl -w "\ndnslookup: %{time_namelookup} \nconnect: %{time_connect} \nappconnect: %{time_appconnect} \npretransfer: %{time_pretransfer} \nredirect: %{time_redirect} \nstarttransfer: %{time_starttransfer} \n---------\ntotal: %{time_total} \nsize: %{size_download}\n" \
-so /dev/null https://curl.haxx.se
# Example for printing all variables and their values by using an external file with the format
curl -o /dev/null -s --write-out '@files/curl.format.txt' https://curl.haxx.se
  • Single binary curl
# Get the archive, extract (notice the xjf parameter to tar) and copy.
wget -O curl.tar.bz2 http://www.magicermine.com/demos/curl/curl/curl-7.30.0.ermine.tar.bz2 && \
tar xjf curl.tar.bz2 && \
cp curl-7.30.0.ermine/curl.ermine curl && \
./curl --help
# tcpdump
curl -O https://raw.githubusercontent.com/yunchih/static-binaries/master/tcpdump
  • Single static binary vi
# vi (vim)
curl -OL https://eldada.jfrog.io/artifactory/tools/x86_64/vi.tar.gz
# jq
curl -OL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
  • Get http code using wget (without curl)
    In cases where curl is not available, use wget to get the http code returned from an HTTP endpoint
wget --spider -S -T 2 www.jfrog.org 2>&1| grep "^ HTTP/"| awk '{print $2}'| tail -1
  • Poor man's top shell scripts (in Linux only!). Good for when top is not installed
    Get CPU and memory usage by processes on the current host. Also useful in Linux based Docker containers

  • Process info (in Linux only!)
    To get process info using its PID or search string: Command line, environment variables. Use procInfo.sh.

  • Add file to WAR file addFileToWar.sh

The proc directory

The /proc file system has all the information about the running processes. See full description in the proc man page.

  • Get current processes running (a simple alternative to ps in case it's missing)
forain$(ls -d /proc/*/);doif [[ -f$a/exe ]];then ls -l ${a}exe;fi;done
# Assume PID is the process ID you are looking at
cat /proc/${PID}/cmdline | tr '\0'''# or
cat /proc/${PID}/cmdline | sed -z 's/$/ /g'
  • Get a process environment variables (see usage in procInfo.sh)
# Assume PID is the process ID you are looking at
cat /proc/${PID}/environ | tr '\0''\n'# or
cat /proc/${PID}/environ | sed -z 's/$/\n/g'
  • Get load average from disk instead of command
cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}'
  • Get top 10 processes IDs and names sorted with highest time waiting for disk IO (Aggregated block I/O delays, measured in clock ticks)
cut -d"" -f 1,2,42 /proc/[0-9]*/stat | sort -n -k 3 | tail -10

Screen

# Start a new session with session name
screen -S <session_name># List running screens
screen -ls
# Attach to a running session
screen -x
# Attach to a running session with name
screen -r <session_name># Detach a running session
screen -d <session_name>
  • Screen commands are prefixed by an escape key, by default Ctrl-a (that's Control-a, sometimes written ^a). To send a literal Ctrl-a to the programs in screen, use Ctrl-a a. This is useful when when working with screen within screen. For example Ctrl-a a n will move screen to a new window on the screen within screen.
DescriptionCommand
Exit and close sessionCtrl-d or exit
Detach current sessionCtrl-a d
Detach and logout (quick exit)Ctrl-a D D
Kill current windowCtrl-a k
Exit screenCtrl-a : quit or exit all of the programs in screen
Force-exit screenCtrl-a C-\ (not recommended)
  • Help
DescriptionCommand
See helpCtrl-a ? (Lists keybindings)

Sysbench

Sysbench is a mutli-purpose benchmark that features tests for CPU, memory, I/O, and even database performance testing.
See full content for this section in linuxconfig.org's how to benchmark your linux system.

  • Installation (Debian/Ubuntu)
sudo apt install sysbench
  • CPU benchmark
sysbench --test=cpu run
  • Memory benchmark
sysbench --test=memory run
  • I/O benchmark
sysbench --test=fileio --file-test-mode=seqwr run

Apache Bench

From the Apache HTTP server benchmarking tool page: "ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server."

# A simple benchmarking of a web server. Running 100 requests with up to 10 concurrent requests
ab -n 100 -c 10 http://www.jfrog.com/

Load generator

A simple createLoad.sh script to create disk IO and CPU load in the current environment. This script just creates and deletes files in a temp directory which strains the CPU and disk IO.
WARNING: Running this script with many threads can bring a system to a halt or even crash it. USE WITH CARE!

./createLoad.sh --threads 10

Git

  • Rebasing a branch on master
# Update local copy of master
git checkout master
git pull
# Rebase the branch on the updated master
git checkout my-branch
git rebase master
# Rebase and squash
git rebase master -i
# If problems are found, follow on screen instructions to resolve and complete the rebase.
  • Resetting a fork with upstream. WARNING: This will override any local changes in your fork!
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master git push origin master --force 
  • Add Signed-off-by line by the committer at the end of the commit log message.
git commit -s -m "Your commit message"

Java

Some useful commands for debugging a java process

# Go to the java/bin directorycd${JAVA_HOME}/bin
# Get your java process id
PID=$(ps -ef | grep java | grep -v grep | awk '{print $2}')# Get JVM native memory usage# For this, you need your java process to run with the the -XX:NativeMemoryTracking=summary parameter
./jcmd ${PID} VM.native_memory summary
# Get all JVM info
./jinfo ${PID}# Get JVM flags for a java process
./jinfo -flags ${PID}# Get JVM heap info 
./jcmd ${PID} GC.heap_info
# Get JVM Metaspace info
./jcmd ${PID} VM.metaspace
# Trigger a full GC
./jcmd ${PID} GC.run
# Java heap memory histogram
./jmap -histo ${PID}

Docker

  • Allow a user to run docker commands without sudo
sudo usermod -aG docker user
# IMPORTANT: Log out and back in after this change!
  • See what Docker is using
docker system df
  • Prune Docker unused resources
# Prune system
docker system prune
# Remove all unused Docker images
docker system prune -a
# Prune only parts
docker image/container/volume/network prune
  • Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
  • Quit an interactive session without closing it:
# Ctrl + p + q (order is important)
  • Attach back to it
docker attach <container-id>
  • Save a Docker image to be loaded in another computer
# Save
docker save -o ~/the.img the-image:tag
# Load into another Docker engine
docker load -i ~/the.img
  • Connect to Docker VM on Mac
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
# Ctrl +A +D to exit
  • Adding an insecure registry in Rancher Desktop

    1. Connect to the Rancher Desktop VM on Mac

      LIMA_HOME="${HOME}/Library/Application Support/rancher-desktop/lima""/Applications/Rancher Desktop.app/Contents/Resources/resources/darwin/lima/bin/limactl" shell 0
    2. Once in the VM

      vi /etc/docker/daemon.json
    3. Edit the file with the insecure registries you want

      {
      "features": {
      "containerd-snapshotter": false
      },
      "insecure-registries": [
      "host.docker.internal",
      "dummy.registry"
      ]
      }
    4. Restart the Docker daemon

      sudo service docker restart
  • Remove none images (usually leftover failed docker builds)

docker images | grep none | awk '{print $3}'| xargs docker rmi
  • Using dive to analyse a Docker image
# Must pull the image before analysis
docker pull redis:latest
# Run using dive Docker image
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest redis:latest
  • Adding health checks for containers that check tcp port being opened without using netcat or other tools in your image
# Check if port 8081 is open
bash -c "</dev/tcp/localhost/8081"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8081 on localhost is open"

Tools

A collection of useful Docker tools

  • A simple terminal UI for Docker and docker-compose: lazydocker
  • A web based UI for local and remote Docker: Portainer
  • Analyze a Docker image with dive

My Dockerfiles

A few Dockerfiles I use in my work

# For a local build
docker build -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 --push .
# For a local build
docker build -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 --push .

Artifactory

See Artifactory related scripts and examples in artifactory

Matrix

A command line effect of the Matrix (the movie) text

whiletrue;doecho$LINES$COLUMNS$((RANDOM %$COLUMNS))$(printf "\U$((RANDOM %500))"); sleep 0.04;done| awk '{a[$3]=0; for (x in a){o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,$4; printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x],x,$4; if (a[x]>=$1){a[x]=0;}}}'

Contribute

Contributing is more than welcome with a pull request

About

A collection of useful commands with various tools

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

189 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Commands example

This is a repository with a collection of useful commands, scripts and examples for easy copy -> paste

Table of contents

Linux

Examples

  • Clear memory cache
sync &&echo 3 | sudo tee /proc/sys/vm/drop_caches
  • Create a self-signed SSL key and certificate
mkdir -p certs/my_com
openssl req -nodes -x509 -newkey rsa:4096 -keyout certs/my_com/my_com.key -out certs/my_com/my_com.crt -days 356 -subj "/C=US/ST=California/L=SantaClara/O=IT/CN=localhost"
  • Create binary files with random content
# Just one file (1mb)
dd if=/dev/urandom of=file bs=1024 count=1024
# Create 10 files of size ~10MBforain {0..9};do \
echo${a}; \
dd if=/dev/urandom of=file.${a} bs=10240 count=1024; \
done
  • Test connection to remote host:port (check port being opened without using netcat or other tools)
# Check if port 8080 is open on remote
bash -c "</dev/tcp/remote/8080"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8080 on host 'remote' is open"
  • Suppress Terminated message from the kill on a background process by waiting for it with wait and directing the stderr output to /dev/null. This is from in this stackoverflow answer.
# Call the kill commandkill${PID}wait$!2>/dev/null
  • curl variables
    The curl command has the ability to provide a lot of information about the transfer. See curl man page.
    Search for --write-out.
    See all supported variables in curl.format.txt
# Example for getting http response code (variable http_code)
curl -o /dev/null -s --write-out '%{http_code}' https://curl.haxx.se
# Example for one-liner printout of several connection time parameters
curl -w "\ndnslookup: %{time_namelookup} \nconnect: %{time_connect} \nappconnect: %{time_appconnect} \npretransfer: %{time_pretransfer} \nredirect: %{time_redirect} \nstarttransfer: %{time_starttransfer} \n---------\ntotal: %{time_total} \nsize: %{size_download}\n" \
-so /dev/null https://curl.haxx.se
# Example for printing all variables and their values by using an external file with the format
curl -o /dev/null -s --write-out '@files/curl.format.txt' https://curl.haxx.se
  • Single binary curl
# Get the archive, extract (notice the xjf parameter to tar) and copy.
wget -O curl.tar.bz2 http://www.magicermine.com/demos/curl/curl/curl-7.30.0.ermine.tar.bz2 && \
tar xjf curl.tar.bz2 && \
cp curl-7.30.0.ermine/curl.ermine curl && \
./curl --help
# tcpdump
curl -O https://raw.githubusercontent.com/yunchih/static-binaries/master/tcpdump
  • Single static binary vi
# vi (vim)
curl -OL https://eldada.jfrog.io/artifactory/tools/x86_64/vi.tar.gz
# jq
curl -OL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
  • Get http code using wget (without curl)
    In cases where curl is not available, use wget to get the http code returned from an HTTP endpoint
wget --spider -S -T 2 www.jfrog.org 2>&1| grep "^ HTTP/"| awk '{print $2}'| tail -1
  • Poor man's top shell scripts (in Linux only!). Good for when top is not installed
    Get CPU and memory usage by processes on the current host. Also useful in Linux based Docker containers

  • Process info (in Linux only!)
    To get process info using its PID or search string: Command line, environment variables. Use procInfo.sh.

  • Add file to WAR file addFileToWar.sh

The proc directory

The /proc file system has all the information about the running processes. See full description in the proc man page.

  • Get current processes running (a simple alternative to ps in case it's missing)
forain$(ls -d /proc/*/);doif [[ -f$a/exe ]];then ls -l ${a}exe;fi;done
# Assume PID is the process ID you are looking at
cat /proc/${PID}/cmdline | tr '\0'''# or
cat /proc/${PID}/cmdline | sed -z 's/$/ /g'
  • Get a process environment variables (see usage in procInfo.sh)
# Assume PID is the process ID you are looking at
cat /proc/${PID}/environ | tr '\0''\n'# or
cat /proc/${PID}/environ | sed -z 's/$/\n/g'
  • Get load average from disk instead of command
cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}'
  • Get top 10 processes IDs and names sorted with highest time waiting for disk IO (Aggregated block I/O delays, measured in clock ticks)
cut -d"" -f 1,2,42 /proc/[0-9]*/stat | sort -n -k 3 | tail -10

Screen

# Start a new session with session name
screen -S <session_name># List running screens
screen -ls
# Attach to a running session
screen -x
# Attach to a running session with name
screen -r <session_name># Detach a running session
screen -d <session_name>
  • Screen commands are prefixed by an escape key, by default Ctrl-a (that's Control-a, sometimes written ^a). To send a literal Ctrl-a to the programs in screen, use Ctrl-a a. This is useful when when working with screen within screen. For example Ctrl-a a n will move screen to a new window on the screen within screen.
DescriptionCommand
Exit and close sessionCtrl-d or exit
Detach current sessionCtrl-a d
Detach and logout (quick exit)Ctrl-a D D
Kill current windowCtrl-a k
Exit screenCtrl-a : quit or exit all of the programs in screen
Force-exit screenCtrl-a C-\ (not recommended)
  • Help
DescriptionCommand
See helpCtrl-a ? (Lists keybindings)

Sysbench

Sysbench is a mutli-purpose benchmark that features tests for CPU, memory, I/O, and even database performance testing.
See full content for this section in linuxconfig.org's how to benchmark your linux system.

  • Installation (Debian/Ubuntu)
sudo apt install sysbench
  • CPU benchmark
sysbench --test=cpu run
  • Memory benchmark
sysbench --test=memory run
  • I/O benchmark
sysbench --test=fileio --file-test-mode=seqwr run

Apache Bench

From the Apache HTTP server benchmarking tool page: "ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server."

# A simple benchmarking of a web server. Running 100 requests with up to 10 concurrent requests
ab -n 100 -c 10 http://www.jfrog.com/

Load generator

A simple createLoad.sh script to create disk IO and CPU load in the current environment. This script just creates and deletes files in a temp directory which strains the CPU and disk IO.
WARNING: Running this script with many threads can bring a system to a halt or even crash it. USE WITH CARE!

./createLoad.sh --threads 10

Git

  • Rebasing a branch on master
# Update local copy of master
git checkout master
git pull
# Rebase the branch on the updated master
git checkout my-branch
git rebase master
# Rebase and squash
git rebase master -i
# If problems are found, follow on screen instructions to resolve and complete the rebase.
  • Resetting a fork with upstream. WARNING: This will override any local changes in your fork!
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master git push origin master --force 
  • Add Signed-off-by line by the committer at the end of the commit log message.
git commit -s -m "Your commit message"

Java

Some useful commands for debugging a java process

# Go to the java/bin directorycd${JAVA_HOME}/bin
# Get your java process id
PID=$(ps -ef | grep java | grep -v grep | awk '{print $2}')# Get JVM native memory usage# For this, you need your java process to run with the the -XX:NativeMemoryTracking=summary parameter
./jcmd ${PID} VM.native_memory summary
# Get all JVM info
./jinfo ${PID}# Get JVM flags for a java process
./jinfo -flags ${PID}# Get JVM heap info 
./jcmd ${PID} GC.heap_info
# Get JVM Metaspace info
./jcmd ${PID} VM.metaspace
# Trigger a full GC
./jcmd ${PID} GC.run
# Java heap memory histogram
./jmap -histo ${PID}

Docker

  • Allow a user to run docker commands without sudo
sudo usermod -aG docker user
# IMPORTANT: Log out and back in after this change!
  • See what Docker is using
docker system df
  • Prune Docker unused resources
# Prune system
docker system prune
# Remove all unused Docker images
docker system prune -a
# Prune only parts
docker image/container/volume/network prune
  • Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
  • Quit an interactive session without closing it:
# Ctrl + p + q (order is important)
  • Attach back to it
docker attach <container-id>
  • Save a Docker image to be loaded in another computer
# Save
docker save -o ~/the.img the-image:tag
# Load into another Docker engine
docker load -i ~/the.img
  • Connect to Docker VM on Mac
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
# Ctrl +A +D to exit
  • Adding an insecure registry in Rancher Desktop

    1. Connect to the Rancher Desktop VM on Mac

      LIMA_HOME="${HOME}/Library/Application Support/rancher-desktop/lima""/Applications/Rancher Desktop.app/Contents/Resources/resources/darwin/lima/bin/limactl" shell 0
    2. Once in the VM

      vi /etc/docker/daemon.json
    3. Edit the file with the insecure registries you want

      {
      "features": {
      "containerd-snapshotter": false
      },
      "insecure-registries": [
      "host.docker.internal",
      "dummy.registry"
      ]
      }
    4. Restart the Docker daemon

      sudo service docker restart
  • Remove none images (usually leftover failed docker builds)

docker images | grep none | awk '{print $3}'| xargs docker rmi
  • Using dive to analyse a Docker image
# Must pull the image before analysis
docker pull redis:latest
# Run using dive Docker image
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest redis:latest
  • Adding health checks for containers that check tcp port being opened without using netcat or other tools in your image
# Check if port 8081 is open
bash -c "</dev/tcp/localhost/8081"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8081 on localhost is open"

Tools

A collection of useful Docker tools

  • A simple terminal UI for Docker and docker-compose: lazydocker
  • A web based UI for local and remote Docker: Portainer
  • Analyze a Docker image with dive

My Dockerfiles

A few Dockerfiles I use in my work

# For a local build
docker build -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 --push .
# For a local build
docker build -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 --push .

Artifactory

See Artifactory related scripts and examples in artifactory

Matrix

A command line effect of the Matrix (the movie) text

whiletrue;doecho$LINES$COLUMNS$((RANDOM %$COLUMNS))$(printf "\U$((RANDOM %500))"); sleep 0.04;done| awk '{a[$3]=0; for (x in a){o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,$4; printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x],x,$4; if (a[x]>=$1){a[x]=0;}}}'

Contribute

Contributing is more than welcome with a pull request

About

A collection of useful commands with various tools

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

189 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Commands example

This is a repository with a collection of useful commands, scripts and examples for easy copy -> paste

Table of contents

Linux

Examples

  • Clear memory cache
sync &&echo 3 | sudo tee /proc/sys/vm/drop_caches
  • Create a self-signed SSL key and certificate
mkdir -p certs/my_com
openssl req -nodes -x509 -newkey rsa:4096 -keyout certs/my_com/my_com.key -out certs/my_com/my_com.crt -days 356 -subj "/C=US/ST=California/L=SantaClara/O=IT/CN=localhost"
  • Create binary files with random content
# Just one file (1mb)
dd if=/dev/urandom of=file bs=1024 count=1024
# Create 10 files of size ~10MBforain {0..9};do \
echo${a}; \
dd if=/dev/urandom of=file.${a} bs=10240 count=1024; \
done
  • Test connection to remote host:port (check port being opened without using netcat or other tools)
# Check if port 8080 is open on remote
bash -c "</dev/tcp/remote/8080"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8080 on host 'remote' is open"
  • Suppress Terminated message from the kill on a background process by waiting for it with wait and directing the stderr output to /dev/null. This is from in this stackoverflow answer.
# Call the kill commandkill${PID}wait$!2>/dev/null
  • curl variables
    The curl command has the ability to provide a lot of information about the transfer. See curl man page.
    Search for --write-out.
    See all supported variables in curl.format.txt
# Example for getting http response code (variable http_code)
curl -o /dev/null -s --write-out '%{http_code}' https://curl.haxx.se
# Example for one-liner printout of several connection time parameters
curl -w "\ndnslookup: %{time_namelookup} \nconnect: %{time_connect} \nappconnect: %{time_appconnect} \npretransfer: %{time_pretransfer} \nredirect: %{time_redirect} \nstarttransfer: %{time_starttransfer} \n---------\ntotal: %{time_total} \nsize: %{size_download}\n" \
-so /dev/null https://curl.haxx.se
# Example for printing all variables and their values by using an external file with the format
curl -o /dev/null -s --write-out '@files/curl.format.txt' https://curl.haxx.se
  • Single binary curl
# Get the archive, extract (notice the xjf parameter to tar) and copy.
wget -O curl.tar.bz2 http://www.magicermine.com/demos/curl/curl/curl-7.30.0.ermine.tar.bz2 && \
tar xjf curl.tar.bz2 && \
cp curl-7.30.0.ermine/curl.ermine curl && \
./curl --help
# tcpdump
curl -O https://raw.githubusercontent.com/yunchih/static-binaries/master/tcpdump
  • Single static binary vi
# vi (vim)
curl -OL https://eldada.jfrog.io/artifactory/tools/x86_64/vi.tar.gz
# jq
curl -OL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
  • Get http code using wget (without curl)
    In cases where curl is not available, use wget to get the http code returned from an HTTP endpoint
wget --spider -S -T 2 www.jfrog.org 2>&1| grep "^ HTTP/"| awk '{print $2}'| tail -1
  • Poor man's top shell scripts (in Linux only!). Good for when top is not installed
    Get CPU and memory usage by processes on the current host. Also useful in Linux based Docker containers

  • Process info (in Linux only!)
    To get process info using its PID or search string: Command line, environment variables. Use procInfo.sh.

  • Add file to WAR file addFileToWar.sh

The proc directory

The /proc file system has all the information about the running processes. See full description in the proc man page.

  • Get current processes running (a simple alternative to ps in case it's missing)
forain$(ls -d /proc/*/);doif [[ -f$a/exe ]];then ls -l ${a}exe;fi;done
# Assume PID is the process ID you are looking at
cat /proc/${PID}/cmdline | tr '\0'''# or
cat /proc/${PID}/cmdline | sed -z 's/$/ /g'
  • Get a process environment variables (see usage in procInfo.sh)
# Assume PID is the process ID you are looking at
cat /proc/${PID}/environ | tr '\0''\n'# or
cat /proc/${PID}/environ | sed -z 's/$/\n/g'
  • Get load average from disk instead of command
cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}'
  • Get top 10 processes IDs and names sorted with highest time waiting for disk IO (Aggregated block I/O delays, measured in clock ticks)
cut -d"" -f 1,2,42 /proc/[0-9]*/stat | sort -n -k 3 | tail -10

Screen

# Start a new session with session name
screen -S <session_name># List running screens
screen -ls
# Attach to a running session
screen -x
# Attach to a running session with name
screen -r <session_name># Detach a running session
screen -d <session_name>
  • Screen commands are prefixed by an escape key, by default Ctrl-a (that's Control-a, sometimes written ^a). To send a literal Ctrl-a to the programs in screen, use Ctrl-a a. This is useful when when working with screen within screen. For example Ctrl-a a n will move screen to a new window on the screen within screen.
DescriptionCommand
Exit and close sessionCtrl-d or exit
Detach current sessionCtrl-a d
Detach and logout (quick exit)Ctrl-a D D
Kill current windowCtrl-a k
Exit screenCtrl-a : quit or exit all of the programs in screen
Force-exit screenCtrl-a C-\ (not recommended)
  • Help
DescriptionCommand
See helpCtrl-a ? (Lists keybindings)

Sysbench

Sysbench is a mutli-purpose benchmark that features tests for CPU, memory, I/O, and even database performance testing.
See full content for this section in linuxconfig.org's how to benchmark your linux system.

  • Installation (Debian/Ubuntu)
sudo apt install sysbench
  • CPU benchmark
sysbench --test=cpu run
  • Memory benchmark
sysbench --test=memory run
  • I/O benchmark
sysbench --test=fileio --file-test-mode=seqwr run

Apache Bench

From the Apache HTTP server benchmarking tool page: "ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server."

# A simple benchmarking of a web server. Running 100 requests with up to 10 concurrent requests
ab -n 100 -c 10 http://www.jfrog.com/

Load generator

A simple createLoad.sh script to create disk IO and CPU load in the current environment. This script just creates and deletes files in a temp directory which strains the CPU and disk IO.
WARNING: Running this script with many threads can bring a system to a halt or even crash it. USE WITH CARE!

./createLoad.sh --threads 10

Git

  • Rebasing a branch on master
# Update local copy of master
git checkout master
git pull
# Rebase the branch on the updated master
git checkout my-branch
git rebase master
# Rebase and squash
git rebase master -i
# If problems are found, follow on screen instructions to resolve and complete the rebase.
  • Resetting a fork with upstream. WARNING: This will override any local changes in your fork!
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master git push origin master --force 
  • Add Signed-off-by line by the committer at the end of the commit log message.
git commit -s -m "Your commit message"

Java

Some useful commands for debugging a java process

# Go to the java/bin directorycd${JAVA_HOME}/bin
# Get your java process id
PID=$(ps -ef | grep java | grep -v grep | awk '{print $2}')# Get JVM native memory usage# For this, you need your java process to run with the the -XX:NativeMemoryTracking=summary parameter
./jcmd ${PID} VM.native_memory summary
# Get all JVM info
./jinfo ${PID}# Get JVM flags for a java process
./jinfo -flags ${PID}# Get JVM heap info 
./jcmd ${PID} GC.heap_info
# Get JVM Metaspace info
./jcmd ${PID} VM.metaspace
# Trigger a full GC
./jcmd ${PID} GC.run
# Java heap memory histogram
./jmap -histo ${PID}

Docker

  • Allow a user to run docker commands without sudo
sudo usermod -aG docker user
# IMPORTANT: Log out and back in after this change!
  • See what Docker is using
docker system df
  • Prune Docker unused resources
# Prune system
docker system prune
# Remove all unused Docker images
docker system prune -a
# Prune only parts
docker image/container/volume/network prune
  • Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
  • Quit an interactive session without closing it:
# Ctrl + p + q (order is important)
  • Attach back to it
docker attach <container-id>
  • Save a Docker image to be loaded in another computer
# Save
docker save -o ~/the.img the-image:tag
# Load into another Docker engine
docker load -i ~/the.img
  • Connect to Docker VM on Mac
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
# Ctrl +A +D to exit
  • Adding an insecure registry in Rancher Desktop

    1. Connect to the Rancher Desktop VM on Mac

      LIMA_HOME="${HOME}/Library/Application Support/rancher-desktop/lima""/Applications/Rancher Desktop.app/Contents/Resources/resources/darwin/lima/bin/limactl" shell 0
    2. Once in the VM

      vi /etc/docker/daemon.json
    3. Edit the file with the insecure registries you want

      {
      "features": {
      "containerd-snapshotter": false
      },
      "insecure-registries": [
      "host.docker.internal",
      "dummy.registry"
      ]
      }
    4. Restart the Docker daemon

      sudo service docker restart
  • Remove none images (usually leftover failed docker builds)

docker images | grep none | awk '{print $3}'| xargs docker rmi
  • Using dive to analyse a Docker image
# Must pull the image before analysis
docker pull redis:latest
# Run using dive Docker image
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest redis:latest
  • Adding health checks for containers that check tcp port being opened without using netcat or other tools in your image
# Check if port 8081 is open
bash -c "</dev/tcp/localhost/8081"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8081 on localhost is open"

Tools

A collection of useful Docker tools

  • A simple terminal UI for Docker and docker-compose: lazydocker
  • A web based UI for local and remote Docker: Portainer
  • Analyze a Docker image with dive

My Dockerfiles

A few Dockerfiles I use in my work

# For a local build
docker build -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 --push .
# For a local build
docker build -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 --push .

Artifactory

See Artifactory related scripts and examples in artifactory

Matrix

A command line effect of the Matrix (the movie) text

whiletrue;doecho$LINES$COLUMNS$((RANDOM %$COLUMNS))$(printf "\U$((RANDOM %500))"); sleep 0.04;done| awk '{a[$3]=0; for (x in a){o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,$4; printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x],x,$4; if (a[x]>=$1){a[x]=0;}}}'

Contribute

Contributing is more than welcome with a pull request

About

A collection of useful commands with various tools

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

189 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Commands example

This is a repository with a collection of useful commands, scripts and examples for easy copy -> paste

Table of contents

Linux

Examples

  • Clear memory cache
sync &&echo 3 | sudo tee /proc/sys/vm/drop_caches
  • Create a self-signed SSL key and certificate
mkdir -p certs/my_com
openssl req -nodes -x509 -newkey rsa:4096 -keyout certs/my_com/my_com.key -out certs/my_com/my_com.crt -days 356 -subj "/C=US/ST=California/L=SantaClara/O=IT/CN=localhost"
  • Create binary files with random content
# Just one file (1mb)
dd if=/dev/urandom of=file bs=1024 count=1024
# Create 10 files of size ~10MBforain {0..9};do \
echo${a}; \
dd if=/dev/urandom of=file.${a} bs=10240 count=1024; \
done
  • Test connection to remote host:port (check port being opened without using netcat or other tools)
# Check if port 8080 is open on remote
bash -c "</dev/tcp/remote/8080"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8080 on host 'remote' is open"
  • Suppress Terminated message from the kill on a background process by waiting for it with wait and directing the stderr output to /dev/null. This is from in this stackoverflow answer.
# Call the kill commandkill${PID}wait$!2>/dev/null
  • curl variables
    The curl command has the ability to provide a lot of information about the transfer. See curl man page.
    Search for --write-out.
    See all supported variables in curl.format.txt
# Example for getting http response code (variable http_code)
curl -o /dev/null -s --write-out '%{http_code}' https://curl.haxx.se
# Example for one-liner printout of several connection time parameters
curl -w "\ndnslookup: %{time_namelookup} \nconnect: %{time_connect} \nappconnect: %{time_appconnect} \npretransfer: %{time_pretransfer} \nredirect: %{time_redirect} \nstarttransfer: %{time_starttransfer} \n---------\ntotal: %{time_total} \nsize: %{size_download}\n" \
-so /dev/null https://curl.haxx.se
# Example for printing all variables and their values by using an external file with the format
curl -o /dev/null -s --write-out '@files/curl.format.txt' https://curl.haxx.se
  • Single binary curl
# Get the archive, extract (notice the xjf parameter to tar) and copy.
wget -O curl.tar.bz2 http://www.magicermine.com/demos/curl/curl/curl-7.30.0.ermine.tar.bz2 && \
tar xjf curl.tar.bz2 && \
cp curl-7.30.0.ermine/curl.ermine curl && \
./curl --help
# tcpdump
curl -O https://raw.githubusercontent.com/yunchih/static-binaries/master/tcpdump
  • Single static binary vi
# vi (vim)
curl -OL https://eldada.jfrog.io/artifactory/tools/x86_64/vi.tar.gz
# jq
curl -OL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
  • Get http code using wget (without curl)
    In cases where curl is not available, use wget to get the http code returned from an HTTP endpoint
wget --spider -S -T 2 www.jfrog.org 2>&1| grep "^ HTTP/"| awk '{print $2}'| tail -1
  • Poor man's top shell scripts (in Linux only!). Good for when top is not installed
    Get CPU and memory usage by processes on the current host. Also useful in Linux based Docker containers

  • Process info (in Linux only!)
    To get process info using its PID or search string: Command line, environment variables. Use procInfo.sh.

  • Add file to WAR file addFileToWar.sh

The proc directory

The /proc file system has all the information about the running processes. See full description in the proc man page.

  • Get current processes running (a simple alternative to ps in case it's missing)
forain$(ls -d /proc/*/);doif [[ -f$a/exe ]];then ls -l ${a}exe;fi;done
# Assume PID is the process ID you are looking at
cat /proc/${PID}/cmdline | tr '\0'''# or
cat /proc/${PID}/cmdline | sed -z 's/$/ /g'
  • Get a process environment variables (see usage in procInfo.sh)
# Assume PID is the process ID you are looking at
cat /proc/${PID}/environ | tr '\0''\n'# or
cat /proc/${PID}/environ | sed -z 's/$/\n/g'
  • Get load average from disk instead of command
cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}'
  • Get top 10 processes IDs and names sorted with highest time waiting for disk IO (Aggregated block I/O delays, measured in clock ticks)
cut -d"" -f 1,2,42 /proc/[0-9]*/stat | sort -n -k 3 | tail -10

Screen

# Start a new session with session name
screen -S <session_name># List running screens
screen -ls
# Attach to a running session
screen -x
# Attach to a running session with name
screen -r <session_name># Detach a running session
screen -d <session_name>
  • Screen commands are prefixed by an escape key, by default Ctrl-a (that's Control-a, sometimes written ^a). To send a literal Ctrl-a to the programs in screen, use Ctrl-a a. This is useful when when working with screen within screen. For example Ctrl-a a n will move screen to a new window on the screen within screen.
DescriptionCommand
Exit and close sessionCtrl-d or exit
Detach current sessionCtrl-a d
Detach and logout (quick exit)Ctrl-a D D
Kill current windowCtrl-a k
Exit screenCtrl-a : quit or exit all of the programs in screen
Force-exit screenCtrl-a C-\ (not recommended)
  • Help
DescriptionCommand
See helpCtrl-a ? (Lists keybindings)

Sysbench

Sysbench is a mutli-purpose benchmark that features tests for CPU, memory, I/O, and even database performance testing.
See full content for this section in linuxconfig.org's how to benchmark your linux system.

  • Installation (Debian/Ubuntu)
sudo apt install sysbench
  • CPU benchmark
sysbench --test=cpu run
  • Memory benchmark
sysbench --test=memory run
  • I/O benchmark
sysbench --test=fileio --file-test-mode=seqwr run

Apache Bench

From the Apache HTTP server benchmarking tool page: "ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server."

# A simple benchmarking of a web server. Running 100 requests with up to 10 concurrent requests
ab -n 100 -c 10 http://www.jfrog.com/

Load generator

A simple createLoad.sh script to create disk IO and CPU load in the current environment. This script just creates and deletes files in a temp directory which strains the CPU and disk IO.
WARNING: Running this script with many threads can bring a system to a halt or even crash it. USE WITH CARE!

./createLoad.sh --threads 10

Git

  • Rebasing a branch on master
# Update local copy of master
git checkout master
git pull
# Rebase the branch on the updated master
git checkout my-branch
git rebase master
# Rebase and squash
git rebase master -i
# If problems are found, follow on screen instructions to resolve and complete the rebase.
  • Resetting a fork with upstream. WARNING: This will override any local changes in your fork!
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master git push origin master --force 
  • Add Signed-off-by line by the committer at the end of the commit log message.
git commit -s -m "Your commit message"

Java

Some useful commands for debugging a java process

# Go to the java/bin directorycd${JAVA_HOME}/bin
# Get your java process id
PID=$(ps -ef | grep java | grep -v grep | awk '{print $2}')# Get JVM native memory usage# For this, you need your java process to run with the the -XX:NativeMemoryTracking=summary parameter
./jcmd ${PID} VM.native_memory summary
# Get all JVM info
./jinfo ${PID}# Get JVM flags for a java process
./jinfo -flags ${PID}# Get JVM heap info 
./jcmd ${PID} GC.heap_info
# Get JVM Metaspace info
./jcmd ${PID} VM.metaspace
# Trigger a full GC
./jcmd ${PID} GC.run
# Java heap memory histogram
./jmap -histo ${PID}

Docker

  • Allow a user to run docker commands without sudo
sudo usermod -aG docker user
# IMPORTANT: Log out and back in after this change!
  • See what Docker is using
docker system df
  • Prune Docker unused resources
# Prune system
docker system prune
# Remove all unused Docker images
docker system prune -a
# Prune only parts
docker image/container/volume/network prune
  • Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
  • Quit an interactive session without closing it:
# Ctrl + p + q (order is important)
  • Attach back to it
docker attach <container-id>
  • Save a Docker image to be loaded in another computer
# Save
docker save -o ~/the.img the-image:tag
# Load into another Docker engine
docker load -i ~/the.img
  • Connect to Docker VM on Mac
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
# Ctrl +A +D to exit
  • Adding an insecure registry in Rancher Desktop

    1. Connect to the Rancher Desktop VM on Mac

      LIMA_HOME="${HOME}/Library/Application Support/rancher-desktop/lima""/Applications/Rancher Desktop.app/Contents/Resources/resources/darwin/lima/bin/limactl" shell 0
    2. Once in the VM

      vi /etc/docker/daemon.json
    3. Edit the file with the insecure registries you want

      {
      "features": {
      "containerd-snapshotter": false
      },
      "insecure-registries": [
      "host.docker.internal",
      "dummy.registry"
      ]
      }
    4. Restart the Docker daemon

      sudo service docker restart
  • Remove none images (usually leftover failed docker builds)

docker images | grep none | awk '{print $3}'| xargs docker rmi
  • Using dive to analyse a Docker image
# Must pull the image before analysis
docker pull redis:latest
# Run using dive Docker image
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest redis:latest
  • Adding health checks for containers that check tcp port being opened without using netcat or other tools in your image
# Check if port 8081 is open
bash -c "</dev/tcp/localhost/8081"2>/dev/null
[ $?-eq 0 ] &&echo"Port 8081 on localhost is open"

Tools

A collection of useful Docker tools

  • A simple terminal UI for Docker and docker-compose: lazydocker
  • A web based UI for local and remote Docker: Portainer
  • Analyze a Docker image with dive

My Dockerfiles

A few Dockerfiles I use in my work

# For a local build
docker build -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-ubuntu-with-tools -t eldada.jfrog.io/docker/ubuntu-with-tools:24.04 --push .
# For a local build
docker build -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 .# Multi arch build and push# If needed, create a buildx builder and use it
docker buildx create --platform linux/arm64,linux/amd64 --name build-amd64-arm64
docker buildx use build-amd64-arm64
# Multi arch build and push
docker buildx build --platform linux/arm64,linux/amd64 -f Dockerfile-alpine-with-tools -t eldada.jfrog.io/docker/alpine-with-tools:3.21.0 --push .

Artifactory

See Artifactory related scripts and examples in artifactory

Matrix

A command line effect of the Matrix (the movie) text

whiletrue;doecho$LINES$COLUMNS$((RANDOM %$COLUMNS))$(printf "\U$((RANDOM %500))"); sleep 0.04;done| awk '{a[$3]=0; for (x in a){o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,$4; printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x],x,$4; if (a[x]>=$1){a[x]=0;}}}'

Contribute

Contributing is more than welcome with a pull request

About

A collection of useful commands with various tools

Topics

Resources

Stars

10 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages