Skip to content

One-liners

Some Bash commands can be written as a “one-liner.” if and while statements, for example, can be written in a slightly different way to chain commands.

Bash Variables

Set variable to path where script was called from

Say you have a path, /home/username/scripts/system/update_system.sh, and your current directory is /home/username/scripts/. If you call ./system/update_system.sh from the /home/username/scripts/ directory, the value of $CWD below would be /home/username/scripts:

CWD=$(pwd)

Set variable to path where script exists

Say you have a path, /home/username/scripts/system/update_system.sh, and your current directory is /home/username/scripts/. If you call ./system/update_system.sh from the /home/username/scripts/ directory, the value of $THIS_DIR below would be /home/username/scripts/system/.

THIS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

Get formatted timestamp

Set a variable to a timestamp when the variable was initialized.

TS=$(date +"%Y-%m-%d %H-%M-%S")

Format the timestamp using +%?, where the ? is one of the below:

ValueDate Part# Digits
%YYear4 (YYYY)
%mMonth2 (mm)
%dDay2 (dd)
%HHour (24h)2 (HH)
%IHour (12h)2 (HH)
%MMinutes2 (MM)
%SSeconds2 (SS)
%pAM/PM (12h only)2 (AM/PM)

You can also create a function and call it in a string to add a timestamp, for example to name a file or directory.

get_timestamp() {
    echo "$(date +"%Y-%m-%d %H:%M:%S")"
}

## Capture output of timestamp in a variable
TS=$(get_timestamp)
echo "Timestamp: $TS"

## Use it in a string
#  Warning: change format to +"%Y-%m-%d %H-%M-%S" to avoid ":" characters in filenames
DIRECTORY_PATH="$(get_timestamp)_pictures"  ## YYYY-mm-dd HH-MM-SS_pictures

find one-liners

The find command on Unix machines searches for files/directories that match a pattern. You can chain commands on the results with -exec <logic> {} +, for example to remove all results of the find command.

Find & remove

You can add an -exec statement to a find command to do something with the results of find.

Find & remove files

find . -type f -name "name-or-namepart" -exec rm {} +

Find & remove dirs

find . -type d -name "name-or-namepart" -exec rm -rf {} +

Search & replace in a file name

Some characters are invalid for filenames, i.e. :, on certain OSes (looking at you, Windows). This command can search for symbols/patterns in a string and replace them. In the example below, we search for any file with a : anywhere in the name and replace it with a - symbol:

find /path/to/your/directory -type f -name '*:*' -exec bash -c 'mv "$0" "${0//:/-}"' {} \;

Exclusion strings

Use ! -exec sh -c 'ls "$1"/<your-find-pattern>/dev/null 2>&1' _ {} \;, replacing <your-find-pattern> with a search string, to write an exclusion list for the find command. This will return all results not matching a given pattern.

Print all directories that do not contain a specific filename pattern

Example: print all directories that do not have a file ending in .part

find . -type d ! -exec sh -c 'ls "$1"/*.part >/dev/null 2>&1' _ {} \; -print

Print every file that does not contain a specific filename pattern

Example: Print every file in the current directory that does not end in .part

find . -type f ! -name '*.part'

hostname one-liners

Get host’s primary IP address

hostname -I | cut -f1 -d' '

Command pipeing

Echo multiple lines into file with EOF

cat <<EOF > /path/to/file.ext
This is a line that will be echoed into the file.
The file's path is /path/to/file.ext

The line above will also be written to the file.
EOF

Pass input response to command

You can prepend a command with the answer to a prompt, like with sudo ufw delete $ruleNum, which prompts the user for a yes/no response to confirm deletion of the rule. This makes scripting ufw more of a challenge. By pipeing your response to the command, you can auto-answer prompts from utilities.

yes | sudo ufw delete "$rule_num"

User & Group commands

Check if Linux user exists

getent passwd "username"

Check if Linux group exists

getent group <group_name> /dev/null

Check if command exists & runs

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

Example with docker command:

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

stat one-liners

Get chmod of a file or directory

stat -c %a $PATH

You can add an alias to your ~/.bash_aliases file to call the stat command with variable directory paths:

alias getchmod=stat -c %a

Misc. one-liners

Get a timestamp

You can call the date command with a string format, i.e. +"%Y-%m-%d_%H:%M", to get a formatted datetime string.

timestamp=$(date +"%Y-%m-%d_%H:%M")

## Usage
#  filename="${timestamp}_filename.ext"
timestamp() { date +"%Y-%m-%d_%H:%M"; }

## Usage
#  current_time=$(timestamp)

Bash Timestamp Cheatsheet

CommandExample Output
timestamp=$(date +%Y%m%d_%H%M%S)20251127_230512
timestamp=$(date +%Y%m%d_%H%M)20251127_23 (no seconds)
timestamp=$(date +%Y-%m-%d_%H-%M-%S)2025-11-27_23-05-12
timestamp=$(date +%Y-%m-%dT%H:%M:%S)2025-11-27T23:05:12
timestamp=$(date -Iseconds)2025-11-27T23:05:12-05:00 (ISO with TZ)
timestamp=$(date +%s)1758812671 (time in seconds since Unix epoch, i.e. January 1st 1970)
timestamp=$(date +%s.%N)1758812671.123456789 (with nanoseconds)
timestamp=$(date +%Y-%m-%d)2025-11-27
timestamp=$(date +%H%M%S)230512
timestamp=$(date +%Y%m%d)20251127
timestamp=$(date +%Y%m%d_%H%M%S_%Z)20251127_230512_EST
timestamp=$(date -u +%Y%m%d_%H%M%S_UTC)20251127_040512_UTC (UTC time)
timestamp=$(date +%F_%T)2025-11-27_23:05:12
timestamp=$(date +"%Y.%m.%d-%H.%M.%S")2025.11.27-23.05.12

Repeat a command with a sleep

You can write a while loop as a one-liner:

while true; do <your command>; sleep <sleep seconds>; done

Example: repeat the ls command every 5 seconds:

while true; do ls; sleep 5; done

Copy or move a file without typing the name twice

Instead of typing:

cp file1.ext file1.ext.bak

You can use:

cp file1.ext{,.bak}

You can do this with the mv command too:

mv file1.ext{,.bak}

To do this in the other direction, i.e. renaming file1.ext.bak to file1.ext:

cp file1.ext{.bak,}

rsync one-liners

Sync path with rsync

rsync is an incredible useful tool for synchronizing files. It can be used to sync local-to-local, remote-to-remote, or local-to-remote/remote-to-local.

rsync flags reference:

argdescription
-rRecursive copy (unnecessary with -a)
-aArchive mode, includes recursive transfer
-zCompress the data
-vVerbose/detailed info during transfer
-hHuman readable output
--progressShow a progress bar during transfer

Sync local file to remote

rsync -avzh --progress /local/path/ user@remote:/remote/path/

Sync remote file to local

rsync -avzh --progress user@remote:/remote/path/ /local/path/

Swap Memory

Clear swap

sudo swapoff -a ; sudo swapon -a
Last updated on