Introduction

The following is a collection of commands for various languages and tools.

This book is generated with mdBook and hosted by GitLab Pages.

See Also

Windows

Search Files.bat

REM From https://stackoverflow.com/a/13799990/11912
findstr /s "<term>" *.item

Battery reporting

# Generate a battery report.
powercfg /batteryreport /output "C:\battery-report.html"

# Sleep study.
powercfg /sleepstudy /output "C:\sleep-study.html"

Linux

Specifically using Ubuntu.

SSH

Type exit to exit out of a SSH session.

# SSH into a server with Raspberry Pi's default user.
ssh pi@<ip_address>

# SSH into a server as a particular user.
ssh <user_name>@<ip_address>

# Output current user's name.
whoami

# View last hour of SSH logs.
sudo journalctl -u ssh --since "1 hour ago"

# Determine shell being used.
ps -p "$$"

# Find process having a process id (PID).
ps -p <pid>

System management

# Reboot/restart.
sudo reboot
sudo shutdown -r now
# Reboot in 5 minutes.
sudo shutdown -r 5

# Shutdown
sudo poweroff

# Get machine and kernel information.
uname -mrs

# Get distribution-specific information.
lsb_release -a

# Get computer name.
hostname

# Get Debian version.
cat /etc/debian_version

Updates

# Get a list of current packages.
sudo apt update

# Get a list of upgradable packages.
apt list --upgradable
apt list --upgradable -a

# Upgrade all packages.
sudo apt upgrade

# Install or update specificed package.
sudo apt install <package-name>

File system

Information

# View disk space.
df
df -h

# Count number of files and folders in home directory.
ls ~ | wc -l

# List block devices. Helps with seeing partition information.
sudo lsblk -f -m

# View the total size of a directory.
sudo du -sh /path/to/directory
# Show by child directory size.
sudo du -h /path/to/directory --max-depth=1
# Show largest directories first.
sudo du -h /path/to/directory --max-depth=1 | sort -hr
# Sort by directory name.
sudo du -h /path/to/directory --max-depth=1 | sort -k2
# Largest directories.
sudo du --separate-dirs -h /path/to/directory | sort -hr | head
sudo du --separate-dirs -h /path/to/directory | sort -hr | head -n 2

# Get all .mp4 files sorted by date and showing date, folder name, file name, and size.
# Excludes ._ and .DS_Store files (macOS).
find . -type f -name "*.mp4" ! -name "._*" ! -name ".DS_Store" -printf "%CY-%Cm-%Cd %CT     %h     %f     %s\n" | sort -n
# Print working directory (current directory).
pwd

# By itself, move to the current user's home directory. Tilde is short for home directory.
cd
cd ~

Modification

# Make a new directory.
mkdir name
mkdir name1 name2 name3

# Make a new directory and sub-directory/ies.
mkdir -p path/to/directory

# Move file(s)/directories to an existing directory.
mv file.txt dir1
mv file1.txt file2.txt dir1
mv file1.txt file2.txt new-dir dir1

# Rename a file.
mv file.txt new-name.txt

# Rename a directory.
mv dir-name new-dir-name

# Copy a file
cp path/to/file.txt .
cp file.txt copy-file.txt

# Remove/delete a file.
rm file.txt

# Remove/delete an empty directory.
rmdir path/to/directory

# Remove/delete a directory, even if it has files. (Only macOS?)
rmdir -r path/to/directory
# Works on Ubuntu.
rm -r path/to/directory

File viewing and creation

# Look at a file or multiple files.
cat file.txt
cat file1.txt file2.txt
cat file?.txt
cat file*

# Write to a file.
echo "Some text" > file.txt
echo "Some more text" >> file.txt

# File viewer. Press q to quit.
less file.txt

# List all files in a directory, with full paths, into a text file.
find wwwroot -type f > files.txt
# The above with directory, file name, file date, and size, into a tab-separated file.
find . -type f ! -name "._*" ! -name ".DS_Store" -printf "%h\t%f\t%CY-%Cm-%Cd %CT\t%s\n" > files.tsv

# Get full path to a file.
readlink -f relative/path/to/file

Hidden content

# Make a hidden directory.
mkdir .dir1

# Make a hidden file.
mkdir .hide.txt

# List all hidden files/folders.
ls -a

System information

# View OS information.
cat /etc/os-release

# View system information on Ubuntu, which is displayed on SSH login:
landscape-sysinfo

# System monitoring.
top
# Prettier version of top.
htop

# Memory usage.
free
# Human readable.
free -h
# Show in MBs.
free -m

# IP address
ip a
hostname -I

# Server uptime.
uptime

# View path variable.
echo $PATH

# Find path of binary.
which cd

Package management

# Show manually installed packages.
apt-mark showmanual
apt list --manual-installed

# List installed packages.
apt list --installed
dpkg --list

sudo dpkg --audit
sudo dpkg --get-selections

User management

# Show who's logged in.
w

# Show the last logged in users.
last

# Show the last bad login attempts.
lastb

# Set the password for a user.
passwd <user>

# List user information, including groups.
id <user>

# List all users.
cat /etc/passwd

# List all users across multiple sources.
getent passwd

# Install sudo on Debian or the like (that don't have it by default).
apt update
apt install sudo

# Grant a user sudo.
usermod -aG sudo <username>
# Add the current user to a group (<group-name>).
sudo usermod -aG <group-name> ${USER}

Permissions

# List all users.
compgen -u
getent passwd

# List all groups.
compgen -g
getent group

# List all groups current user is in.
groups
# List all groups a user (username) is in.
groups username

# Add write access to group.
chmod g+w file-or-directory

# Remove write and execute from group.
chmod g-wx file-or-directory

# Remove read, write, and execute from others.
chmod o-rwx file-or-directory

# Users, groups, and others have read, write, and execute.
chmod ugo+rwx file-or-directory

# Grant all users read-only access to a file or directory.
chmod a=r file-or-directory

# View permissions.
ls -l
ls -ld

Service logs

# View logs for a particular service.
sudo journalctl -fu mycustom.service
sudo journalctl -fu mycustom.service --since "1 hour ago"

Copy files

# Copy a file to a directory.
scp file-name.ext <user>@<server>:~/path/to/directory/

# Copy the contents of a folder to a remote folder.
scp -r .\path\to\directory\* <user>@<server>:/path/to/remove/directory

Sudo

# Start a root shell. `exit` when done.
sudo -s

Firewall (ufw)

# Show status of firewall. If active, also lists rules.
sudo ufw status
# Show rules even when ufw is inactive.
sudo ufw show added

# Allow by service.
sudo ufw allow ssh
# Allows 80 and 443.
sudo ufw allow 'Nginx Full'

# Allow port-number.
sudo ufw allow <port-number>
sudo ufw allow 8080

nginx

Configuration

# Test/verify configuration.
sudo nginx -t

# View base configuration.
sudo cat /etc/nginx/nginx.conf

# View default site configuration.
sudo cat /etc/nginx/sites-enabled/default

# List enabled sites.
ls -l /etc/nginx/sites-enabled/

# List available sites.
ls /etc/nginx/sites-available/

# Enable site via a symbolic link.
sudo ln -s /etc/nginx/sites-available/SITE_CONFIG_FILE_NAME /etc/nginx/sites-enabled/

# Remove symbolic link/enabled site.
sudo rm SITE_CONFIG_FILE_NAME
sudo unlink SITE_CONFIG_FILE_NAME
# Remove with confirmation.
sudo rm -i SITE_CONFIG_FILE_NAME

Logging

# View access logs.
sudo cat /var/log/nginx/access.log

Management

# Restart nginx.
sudo systemctl restart nginx

Raspberry Pi Commands

Note to self: Information about Pis I own can be found at https://strivinglife.gitlab.io/book-raspberry-pi/.

Current Uptime

uptime

Restarting

sudo reboot

Shutdown

sudo shutdown -h now

Internet Configuration

ifconfig

# Try to bring a network interface up.
sudo ifup wlan0

Samba

# Restart Samba services.
sudo /etc/init.d/samba restart

# Backup copy of Samba configuration.
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.old
# Edit Samba configuration. Restart (see above) for changes to be picked up.
sudo nano /etc/samba/smb.conf

# Check Samba services.
systemctl status smbd

SSH

# Check SSH service status.
systemctl status sshd

# SSH into a server with Raspberry Pi's default user.
# Enter `exit` and press enter to quit the session.
ssh pi@<ip_address>

Terminal

# View past commands.
history

# View process information
top

Drive Information

# List device information.
sudo fdisk -l

# List mounts.
sudo mount -l

# Example: cd into a mounted USB device.
cd /media/usbhdd1

USB/Port Information

# Basic list of each port.
lsusb
# Lists out each port, with Product if there's a connected device.
usb-devices

Display Information

# List information about the connected display.
tvservice -s

Hardware Information

See https://elinux.org/RPi_HardwareHistory#Board_Revision_History for more information.

# Includes Hardware and Revision information.
cat /proc/cpuinfo

OS Information

cat /etc/os-release

RetroPie audio issues

  1. Make sure the correct audio output device is selected in the RetroPie configuration.
  2. sudo nano /boot/config.txt and uncomment #hdmi_drive=2. ctrl+o, enter, ctrl+x, sudo reboot.

Start GUI

startx

Linux Directories

From root (cd /):

  • /bin essential executables, always available
  • /sbin essential super user executables
  • /lib shared common libraries (for bin and sbin)
  • /etc (editable text configuration)
  • /usr
    • /usr/local
      • /usr/local/bin locally compiled binaries
    • /usr/bin installed binaries for users
  • /home user data
    • /home/___ individual user directory (also ~)
  • /boot required to boot the system (like Linux kernel)
  • /dev devices/hardware/drivers
  • /opt optional/add-on software, rarely will be used
  • /var variable files that change as the system is used (like log and cache files)
  • /tmp temporary files
  • /proc running processes

Detailed in the Filesystem Hierarchy Standard.

macOS

Homebrew

brew update
# Install example.
brew install git
# List outdated formulae.
brew outdated
brew upgrade

Angular

Information has been migrated to Angular Framework Notes.

.NET

  • dotnet new
    • dotnet new list
    • dotnet new gitignore adds a .gitignore to the current directory.
# View .NET installed versions and information.
dotnet --info
# Restore packages.
dotnet restore

dotnet watch run

Environment variables

# launchSettings.json can typically set these.
# See https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-7.0#development-and-launchsettingsjson
$Env:ASPNETCORE_ENVIRONMENT = "Development"
$Env:NETCORE_ENVIRONMENT = "Development"

The ASPNETCORE_ENVIRONMENT value overrides DOTNET_ENVIRONMENT.

Entity Framework Core Tools

CLI reference.

# Install a tool globally.
dotnet tool install --global dotnet-ef

# Update a tool to the latest version.
dotnet tool update --global dotnet-ef

# List installed tools.
dotnet tool list -g

# Search for tools matching `searchTerm`.
dotnet tool search searchTerm

Add SQLite

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Data source=./Database/name.db"
  }
}

Data/DataContext.cs

using API.Models;
using Microsoft.EntityFrameworkCore;

namespace API.Data
{
    public class DataContext : DbContext
    {
        public DbSet<Thing> Things { get; set; }

        public DataContext(DbContextOptions options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}

Program.cs

// Add near the top.
builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});

// Optional: apply migrations on startup. Add after builder.Build().
using (var scope = app.Services.CreateScope()) {
    var db = scope.ServiceProvider.GetRequiredService<DataContext>();
    db.Database.Migrate();
}

Create Initial Migration

dotnet ef migrations add InitialCreate -o Data/Migrations
dotnet ef database update

.NET Examples

Example: .NET API with Angular Frontend and XUnit Testing

This example sets up a new .NET webapi project with XUnit testing and an Angular frontend.

# From repo root:
dotnet new sln
dotnet new webapi -o API
dotnet sln add API
dotnet new gitignore
git init
git add .
git commit -m "Add new .NET webapi project and solution"

# XUnit project.
dotnet new xunit -o API.Tests
dotnet add .\API.Tests\API.Tests.csproj reference .\API\API.csproj
dotnet sln add API.Tests
git add .
git commit -m "Add new XUnit project"

# Create Angular application.
ng new client
git add .
git commit -m "Add new Angular application"

Project Workspace via Windows Terminal

wt -d .\ --title 'Repo Root' `; nt -d .\client\ --title 'ng serve' `; split-pane -H -d .\API\ --title 'dotnet watch run' `; nt -d .\client\src\app\ --title 'ng g ...'`; nt -d .\client\ --title 'ng test' `; split-pane -H -d .\ --title 'dotnet test'

Alternatively

# From repo root:
cd .\API\
dotnet run

# From repo root:
dotnet test

# From repo root:
cd .\client\
ng serve

# From repo root:
cd .\client\
ng test

GDScript Basics

Go

# Initialize a new module.
go mod init example.com/hello

# Run the current directory.
go run .

# Update and cleanup go.mod.
go mod tidy

# Run tests (in files that end with _test.go).
go test
go test -v

# testing.Short() returns true. Useful for t.Skip()ing long/integration tests.
go test -short

# Generate a platform-specific application.
go build

# Install the current application to the Go path.
go install

Information

# Get Go's version.
go version

# Find where the current module would be installed to.
go list -f '{{.Target}}'

# List environment information, including where packages are installed via go get.
go env

Requirements

# Update go.mod to point a module to a local directory.
go mod edit -replace example.com/greetings=../greetings

# Get an external module and add to go.mod require.
go get golang.org/x/example

# Get dependencies for code in the current directory (already added as an import).
go get .

Workspaces

# Initialize a workspace with an existing module.
go work init ./hello

# Add a child module directory to the workspace.
go work use ./example

Utilities

# Generate a TLS/SSL cert. Get GOPATH from `go env`.
go run 'C:\Program Files\Go\src\crypto\tls\generate_cert.go' --rsa-bits=2048 --host=localhost

Testing

# Get basic test coverage, per file.
go test -cover ./...

# Generate a coverage report by method and function.
go test -coverprofile='profile.out' ./...
# Read the report and output to the command line.
go tool cover -func='profile.out'
# Read the report and output to HTML.
go tool cover -func='profile.out'
# Generate a coverage report with number of times each statement is executed during testing.
# Use -covermode=atomic if running any tests in parallel.
go test -covermode=count -coverprofile='profile.out' ./...

T-SQL

Get all tables in a database.

SELECT TABLE_SCHEMA, TABLE_NAME
FROM <database_name>.INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_SCHEMA, TABLE_NAME

Get all views in a database.

SELECT TABLE_SCHEMA, TABLE_NAME
FROM <database_name>.INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'VIEW'
ORDER BY TABLE_SCHEMA, TABLE_NAME

Get all stored procedures in a database.

SELECT SPECIFIC_SCHEMA, SPECIFIC_NAME
FROM <database_name>.INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
ORDER BY SPECIFIC_SCHEMA, SPECIFIC_NAME

Table altering, in T-SQL

Change table schema

Change the schema on an existing table.

ALTER SCHEMA projectManagement
TRANSFER dbo.RequestPriority

Change column

Alter a column in an existing table.

ALTER TABLE [projectManagement].[Task]
ALTER COLUMN Name varchar(250) not null

Add identity and primary key

Add a new identity column to an existing table.

-- See http://stackoverflow.com/a/3698824/11912
ALTER TABLE JobSupplies add Id INT IDENTITY
ALTER TABLE JobSupplies add constraint PK_JobSupplies primary KEY(Id)

PostgreSQL

Unless otherwise noted, non-SQL commands are running under Ubuntu.

# On Ubuntu, run psql as default postgres user.
sudo -u postgres psql

# List all databases.
sudo -u postgres psql -l
-- List all databases.
\l

-- Quit psql.
\q

Configuration

# Show the full path to the PostgreSQL configuration file.
sudo -u postgres psql -c 'SHOW config_file'
# Example: /etc/postgresql/12/main/postgresql.conf

# Show the full path to the HBA configuration file.
sudo -u postgres psql -c 'SHOW hba_file'
# Example: /etc/postgresql/12/main/pg_hba.conf
-- Locate the HBA configuration file.
SHOW hba_file;
-- Example: /etc/postgresql/12/main/pg_hba.conf

-- Or just query the file for rules.
select * from pg_hba_file_rules();

User management

-- List all users.
\du

-- Create a new user.
CREATE USER <name>;

Database management

# Create a new database.
sudo -u postgres createdb <name>
# Verify it was created.
sudo -u postgres psql -l

# Create a new database, echoing out the commands run.
sudo -u postgres createdb <name> -e

# Drop a database.
sudo -u postgres dropdb <name>

SQLite

For a CLI on Windows, download sqlite-tools-win32-x86-___.zip

Import a tsv file into a new database.

This assumes the tsv has a header row.

.open files.sqlite3
.mode tabs
.import files.tsv files

Node

Upgrade npm

npm install npm@latest -g

View versions of a package

npm view package-name versions

Global Packages

Find all globally installed packages

npm ls -g --depth 0

Install/update a package globally

npm install http-server -g

Find outdated global packages

npm outdated -g --depth=0

Auditing

Find any production packages with vulnerabilities. Id est, ignore any development packages.

npm audit --production

Determine why a package is required.

npm why package-name

My Node Globals

The following is a list of globals I tend to install with Node. Items are listed in order of relative importance, and then alphabetically.

npm install ___ -g
npm install -g ___

Again, you can run npm ls -g --depth 0 to view any packages that have been installed globally.

Node Utilities

  • npm-check-updates

General Utilities

  • http-server

TypeScript

  • typescript
  • eslint
  • typedoc
  • dts-gen

Frameworks

  • @angular/cli
  • @ionic/cli
  • @vue/cli
  • create-react-app
  • gulp-cli

Visual Studio Code Extension Development

  • yo
  • generator-code

PowerShell

List all files with a particular extension in the current directory and its children, with results sorted by full file name.

Get-ChildItem -Path .\ -Filter *.sln -Recurse -File | Select Fullname | Sort-Object Fullname

List the 10 largest files in the current directory and subdirectories.

gci -r | sort Length -desc | select @{n="Length";e={$_.length}}, fullname -f 10

Search Files.ps1

Get-ChildItem -Recurse -Include *.item | select-string "<term>"
gci -r -i *.item | select-string "<term>"
gci -r -i *.* -exclude *.dll,*.xml | select-string "<term>"

Search with Git Grep.ps1

# Can only be run within a Git repository, but this will also search untracked files, as well as those that are tracked.
git grep --untracked '<term>'

View a file's contents

Get-Content .\path\to\file.ext

Environment variables

Get all environment variables.

dir Env:

Get environment variables at a certain scope.

[System.Environment]::GetEnvironmentVariables('User')
[System.Environment]::GetEnvironmentVariables('Machine')

Get a particular environment variable.

[Environment]::GetEnvironmentVariable("NAME_OF_VARIABLE")
[Environment]::GetEnvironmentVariable("NAME_OF_VARIABLE", "Machine")
[Environment]::GetEnvironmentVariable("NAME_OF_VARIABLE", "User")

Set an environment variable

$Env:NAME_OF_VARIABLE = "value"

Remove an environment variable

Remove-Item Env:\NAME_OF_VARIABLE

PowerShell Profile

Refresh PowerShell Profile

. $profile

My Windows PowerShell Profile

Import-Module Terminal-Icons
Import-Module PSReadLine

Set-PSReadLineOption -PredictionSource History

oh-my-posh init pwsh --config ~/OneDrive/Apps/oh-my-posh/aritraroy.omp.json | Invoke-Expression

function Set-Title {
<#
.Description
Set-Title sets the window/tab title, such as for Windows Terminal.
#>
	param(
		[Parameter(Mandatory = $true)]
		[string]
		$title
	)
	$Host.UI.RawUI.WindowTitle = $title
}

function Set-Title-Folder {
<#
.Description
Set-Title-Folder sets the window/tab title, such as for Windows Terminal, based on the current folder.
#>
	$Host.UI.RawUI.WindowTitle = Split-Path -Path (Get-Location) -Leaf
}

function Start-ExtensionOpen {
<#
.Description
Start-ExtensionOpen opens a single file with a matching extension, if possible.
#>
	param(
		[string]
		$FileExtension
	)
	$matchingFiles = Get-ChildItem . -Filter *.$FileExtension
	$matchCount = ($matchingFiles | Measure-Object).Count

	if ($matchCount -eq 1) {
		Write-Output "Opening $($matchingFiles.Name)"
		Invoke-Item $matchingFiles[0]
	} elseif ($matchCount -eq 0) {
		Write-Error "No matching files for $($FileExtension)"
	} else {
		Write-Output $matchingFiles.Name
	}
}

Docker

Unless otherwise noted, commands run on Ubuntu 22.

Setup

# Add the current user to the docker group so docker can be run without sudo.
sudo usermod -aG docker ${USER}
su - ${USER}
exit

Basics

# Get installed version.
docker -v

# Verify Docker is setup / run the Hello World image.
sudo docker run hello-world

# Check whether Docker is running.
sudo systemctl status docker

# Search Docker Hub for all images matching a search term (<term>).
docker search <term>

# Show all downloaded images.
docker images

# Remove an image.
docker rmi <image-id>

Containers

# List running containers.
docker ps
# List all containers.
docker ps -a

# Start a container with <container-id> or <container-name>.
docker start <container-id>
docker start <container-name>

# Stop a container.
docker stop <container>

# Restart a container.
docker restart <container>

# Remove/delete a container.
docker rm <container>

# View container's logs.
docker logs <container>

Working with Running Containers

docker cp path/to/file <container>:./destination/path/

# Run bash on the container, if installed.
docker exec -it <container> bash

System

# Show disk usage.
docker system df
docker system df --verbose

# Show active container stats.
docker stats

# View and prune images.
docker image ls --filter dangling=true
docker image prune

Compose

# Stop based upon docker-compose.yml in directory.
docker compose stop

# Start services based upon docker-compose.yml.
docker compose up -d

Install on Ubuntu

On Ubuntu, from https://docs.docker.com/engine/install/ubuntu/:

sudo apt-get update
sudo apt-get install ca-certificates curl gnupg

sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg

echo \
  "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

sudo apt-get update

sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# Test.
sudo docker run hello-world

Windows Terminal

Open a new Windows Terminal window.

wt

Open a new tab in the current window.

wt -w 0

Visual Studio

Install particular NuGet package.ps1

# Installs a particular version of a package.
# See http://stackoverflow.com/q/16126338/11912
Install-Package jQuery -Version 1.10.2

Team Foundation Server

Last reviewed around November 2013.

Delete workspace for user.bat

REM Run from VS developer command prompt
tf workspace /delete _workspace_;_domain_\_user_ /server:http://_server_:8080/tfs
PAUSE

List all workspaces.bat

REM Run from VS developer command prompt
tf workspaces /server:http://_server_:8080/tfs /owner:*
PAUSE