Skip to content

Instantly share code, notes, and snippets.

@wmakeev
Last active November 20, 2022 07:31
Show Gist options
  • Save wmakeev/1125497dbd440e81f33f72bee17e202f to your computer and use it in GitHub Desktop.
Save wmakeev/1125497dbd440e81f33f72bee17e202f to your computer and use it in GitHub Desktop.
Bash cheat sheet #bash #cli #cheatsheet #osx

Основные сочетания клавиш

Сочетание Описание Действие
CTRL+E перемещение курсора в конец строки
CTRL+A перемещение курсора в начало строки
Meta+F →␣ перемещение к следующему слову
Meta+B ␣← перемещение к предыдущему слову
CTRL+K ✂︎⇥ вырезать текст от курсора до конца строки
CTRL+U ⇤✂︎ вырезать текст от курсора до начала строки
CTRL+Y 📋→ вставить текст из буфера
CTRL+D удалить символ перед курсором
Meta+D ⌦␣ удалить слово перед курсором
CTRL+- отмена последнего действия

Meta is your Alt key, normally. For Mac OSX user, you need to enable it yourself. Open Terminal > Preferences > Settings > Keyboard, and enable Use option as meta key. Meta key, by convention, is used for operations on word.

Shortcuts to move faster in Bash command line

Полезные команды (macOS)

Ключ Описание
-R содержимое подкаталогов рекурсивно
-l отобразить атрибуты объектов
-m сожержимое через запятые
-a показать скрытые элементы
-al комбинирование ключей -a и -l (к примеру)
❗️--full-time using ls -al --full-time in OSXgls

gls

> brew install coreutils для использования gls

Ключ Описание
(без аргументов) или ~ перемещение в рабочий каталог
- вернуться в предыдущий каталог

Копирование папок с содежимым с ключем -R

man

Ключ Описание
-k [фраза поиска] или apropos поиск команды по ее описанию
-f [команда] или whatis отобразить описание команды

Навигация

Сочетание Описание Действие
F следующая страница
B предыдущая страница
CTRL+N перемещение на строку вниз
CTRL+P перемещение на строку вверх
Q выйти
/ + текст 🔍 поиск по тексту
N 🔍→ переход к след. вхождению фразы поиска
SHIFT+N ←🔍 предыдущее

Прочие

Команда Описание
pwd Print Working Directory - the absolute pathname of the current folder (i.e. it tells you where you are).
touch Change file timestamps. Sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.
mkdir Make Directory (Create folders)
which Locate a program file in the user's path
cat Concatenate and print (display) the content of files.
less Просмотр stdin команды
chown Change file owner and/or group

mv, rm, rmdir, whereis, whatis -w ls*, whoami

Разное

Имена файлов с пробелами в командах помещаются в кавычки cp 'test 2.txt' test3.txt

Объединение команд

Оператор Описание
; последовательное выполение команд без проверки результата предыдущей команды
&& выполнение следующей команды при УСПЕШНОМ выполнения предыдущей
|| выполнение следующей команды при НЕ УСПЕШНОМ выполнения предыдущей
$([команда]) использование выходных данных одной команды в другой mkdir $(date "+%Y-%m-%d")
| канал - соединение stdout одной команды с stdin другой
> перенаправление stdout команды в файл
>> перенаправление stdout команды с дозаписью в конец файла
< передача в stdin команды содержимого файла echo < test.txt или cat test.txt | echo

Потоки ввода/вывода

Поток Дескриптор Описание
stdin 0 стандартный поток ввода
stdout 1 стандартный поток вывода
stderr 2 стандартный поток ошибок

Bash скрипты

#! - shebang

#!/bin/bash

Example Description
$1, $2, ... The first, second, etc command line arguments to the script.
variable=value To set a value for a variable. Remember, no spaces on either side of =
Quotes " ' Double will do variable substitution, single will not.
variable=$( command ) Save the output of a command into a variable
export var1 Make the variable var1 available to child processes.
Example Description
read varName Read input from the user and store it in the variable varName.
/dev/stdin A file you can read to get the STDIN for the Bash script
Operator Operation
+, -, /*, / addition, subtraction, multiply, divide
var++, var-- Increase and decrease the variable var by 1
% Modulus (Return the remainder after division)
Example Description
let expression Make a variable equal to an expression.
expr expression print out the result of the expression.
$(( expression )) Return the result of the expression.
${#var} Return the length of the variable var.

There are several ways in which to do arithmetic in Bash scripts. Double parentheses is the preferred method.

if

if [ <some test> ]
then
  <commands>
elif [ <some test> ] 
then
  <different commands>
else
  <other commands>
fi
Operator Description
! EXPRESSION The EXPRESSION is false.
-n STRING The length of STRING is greater than zero.
-z STRING The lengh of STRING is zero (ie it is empty).
STRING1 = STRING2 STRING1 is equal to STRING2
STRING1 != STRING2 STRING1 is not equal to STRING2
INTEGER1 -eq INTEGER2 INTEGER1 is numerically equal to INTEGER2
INTEGER1 -gt INTEGER2 INTEGER1 is numerically greater than INTEGER2
INTEGER1 -lt INTEGER2 INTEGER1 is numerically less than INTEGER2
-d FILE FILE exists and is a directory.
-e FILE FILE exists.
-r FILE FILE exists and the read permission is granted.
-s FILE FILE exists and it's size is greater than zero (ie. it is not empty).
-w FILE FILE exists and the write permission is granted.
-x FILE FILE exists and the execute permission is granted.

Expressions used with if

case

case <variable> in
<pattern 1>)
  <commands>
  ;;
<pattern 2>)
  <other commands>
  ;;
esac

The square brackets ( [ ] ) in the if statement above are actually a reference to the command (test)[https://ss64.com/osx/test.html].

Example Description
if Perform a set of commands if a test is true.
else If the test is not true then perform a different set of commands.
elif If the previous test returned false then try this one.
&& Perform the and operation.
|| Perform the or operation.
case Choose a set of commands to execute depending on a string matching a particular pattern.

While

while [ <some test> ]
do
  <commands>
done

Example:

counter=1

while [ $counter -le 10 ]
do
  echo $counter
  ((counter++))
done

echo All done

Until

until [ <some test> ]
do
  <commands>
done

For

for var in <list>
do
  <commands>
done

The list is defined as a series of strings, separated by spaces.

Example:

names='Stan Kyle Cartman'

for name in $names
do
  echo $name
done

echo All done

ranges

We can also process a series of numbers

for value in {1..5} # also possible to specify like {10..0..2}
do
  echo $value
done

Convert a series of .html files over to .php files

for value in $1/*.html
do
  cp $value $1/$( basename -s .html $value ).php
done

Controlling Loops

Break

for value in $1/*
do
  used=$( df $1 | tail -1 | awk '{ print $5 }' | sed 's/%//' )
  if [ $used -gt 90 ]
  then
    echo Low disk space 1>&2
    break
  fi
  cp $value $1/backup/
done

Continue

use continue like break

select var in <list>
do
  <commands>
done
function_name () {
  <commands>
}
function function_name {
  <commands>
}

We may send data to the function in a similar way to passing command line arguments to a script. We supply the arguments directly after the function name. Within the function they are accessible as $1, $2, etc.

Example:

print_something () {
  echo Hello $1
  return 5 # set return status to $?
}

print_something Mars
print_something Jupiter

echo The previous function has a return value of $?
Hello Mars
Hello Jupiter
The previous function has a return value of 5

Typically a return status of 0 indicates that everything went successfully. A non zero value indicates an error occurred.

Example with Command Substitution:

lines_in_file () {
  cat $1 | wc -l
}

num_lines=$( lines_in_file $1 )

Variable Scope

By default a variable is global. We may also create a variable as a local variable. When we create a local variable within a function, it is only visible within that function.

local var_name=<var_value>

Прочее

{aa,bb,cc,dd}  => aa bb cc dd
{0..12}        => 0 1 2 3 4 5 6 7 8 9 10 11 12
{3..-2}        => 3 2 1 0 -1 -2
{a..g}         => a b c d e f g
{g..a}         => g f e d c b a
a{0..3}b       => a0b a1b a2b a3b
{a,b{1..3},c}  => a b1 b2 b3 c
mv app/ss64/alpha.py app/ss64/alphabeta.py
mv app/ss64/{alpha,alphabeta}.py
mv app/ss64/alpha{,beta}.py

> echo /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
/usr/ucb/ex /usr/ucb/edit /usr/lib/ex?.?* /usr/lib/how_ex

Разные скрипты

rm -rf dist || : && mkdir -p dist
@wmakeev
Copy link
Author

wmakeev commented Aug 7, 2018

Задача 1

Нужно вывести список файлов в формате 2018.08.01 14:23:15,20180801-1630710431-8176.CR2 и отфильтровать по типу файла CR2

  1. stat -l -t '%Y.%m.%d %T' *
-rwxrwxrwx 1 mvv staff 1245988 2018-08-01 14:48:26 20180801-1630710431-8175.JPG
-rwxrwxrwx 1 mvv staff 19124833 2018-08-01 14:49:04 20180801-1630710431-8176.CR2
-rwxrwxrwx 1 mvv staff 667172 2018-08-01 14:49:02 20180801-1630710431-8176.JPG

Описание формата для -t strftime

  1. stat -l -t '%Y.%m.%d %T' * | awk {'print $6" "$7","$8'}
2018.08.01 14:48:26,20180801-1630710431-8175.JPG
2018.08.01 14:49:04,20180801-1630710431-8176.CR2
2018.08.01 14:49:02,20180801-1630710431-8176.JPG
  1. stat -l -t '%Y.%m.%d %T' * | awk {'print $6" "$7","$8'} | grep CR2
2018.08.01 14:47:54,20180801-1630710431-8174.CR2
2018.08.01 14:48:26,20180801-1630710431-8175.CR2
2018.08.01 14:49:04,20180801-1630710431-8176.CR2

#time #format

@wmakeev
Copy link
Author

wmakeev commented Aug 9, 2018

test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)

Read from stdin

while read line
do
  echo "$line"
done < /dev/stdin
while read line
do
  echo "$line"
done < "${1:-/dev/stdin}"
  • как работает read?

@wmakeev
Copy link
Author

wmakeev commented Aug 10, 2018

echo

echoerr() { printf "%s\n" "$*" >&2; }

@wmakeev
Copy link
Author

wmakeev commented Mar 11, 2019

Time format

YYYY-MM-DD format date in shell script

DATE=`date '+%Y-%m-%d %H:%M:%S'` # 2019-03-11 16:12:42

@wmakeev
Copy link
Author

wmakeev commented Mar 11, 2019

Variables in string

folder=$1
date=$(date +%Y-%m-%d)
file="$folder/${date}_report.json"

@wmakeev
Copy link
Author

wmakeev commented Mar 23, 2019

Перенаправление stdout и stderr в файл

command > output.txt 2>&1

@wmakeev
Copy link
Author

wmakeev commented Mar 24, 2019

Настройка цветов

.bash_profile

# user@computer:~/path$
export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ "

@wmakeev
Copy link
Author

wmakeev commented Jul 13, 2019

Exit on error

#!/bin/bash

set -e

# some script

@wmakeev
Copy link
Author

wmakeev commented Sep 23, 2019

Count open files by process

lsof -n | sed -E 's/^[^ ]+[ ]+([^ ]+).*$/\1/' | uniq -c | sort | tail

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