Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Feb 10, 2014

Unix as IDE. Man

man -k someterm
apropos someterm

info -k printf
info coreutils printf

Dec 30, 2013

Unix as IDE. History

Execute last command again:
sudo !!
echo !! > new_script.sh
!! | grep Linux

Execute last command started with ls:
!ls

Arguments:
ls !^  # first arg of prev cmd
ls !$  # last arg of prev cmd
ls !*  # all args of prev cmd
ls !ls:2  # second arg of prev ls cmd

Execute command with given history number:
!2039

Hide command from history (use space before cmd):
 ls ~/eagle

Oct 12, 2013

Find out current working directory of a running process?

pwdx <PID>
lsof -p <PID> | grep cwd
readlink -e /proc/<PID>/cwd

Aug 30, 2013

Explain Shell

http://explainshell.com/

This site contains 29761 parsed manpages from sections 1 and 8 found in Ubuntu's manpage repository. A lot of heuristics were used to extract the arguments of each program, and there are errors here and there, especially in manpages that have a non-standard layout.

It is written in Python and uses a bit of NLTK (to find the interesting parts of the manpage), a little d3.js (for the connecting lines graphic) and Flask. It is served with uwsgi and nginx. I will open source the code in the near future, when I have time to clean it up a bit.


Jul 4, 2013

I want to know when a running process will terminate. How can I watch it?

http://askubuntu.com/questions/313138/i-want-to-know-when-a-running-process-will-terminate-how-can-i-watch-it
while [ -d /proc/ ]; do sleep 1; done; echo "Process finished at $(date +"%F %T")."
Or you can make a bash script:
#!/bin/bash

if [ ! -d /proc/$1 ]; then
    echo "Process $1 doesn't exist."
    exit 1
fi

while [ -d /proc/$1 ]; do
    sleep 1
done

echo "Process $1 finished at $(date +"%F %T")."

Mar 9, 2013

How can one run multiple programs in the background with single command?

The bash manpage section titled Compound Commands has two options that would work, list and group commands.

A group command is a series of commands enclosed in curly braces {}. A list is the same, enclosed in parentheses (). Both can be used to background multiple commands within, and finally to background the entire collection as a set. The list construct executes commands in a subshell, so variable assignments are not preserved.

To execute a group of commands:
{ command1 & command2 & } &

You can also execute your commands in a list (subshell):
( command1 & command2 ) &

Note that the list () syntax executes the enclosed commands in a subshell, so variables are not preserved within.

Nov 9, 2012

Gnome terminal jellybeans theme

Original colors from jellybeans vim color theme: https://raw.github.com/nanotech/jellybeans.vim/master/ansi-term-colors.txt

Python: calculate lighter/darker RGB colors http://chase-seibert.github.com/blog/2011/07/29/python-calculate-lighterdarker-rgb-colors.html
>>> def color_variant(hex_color, brightness_offset=40):
...         rgb_hex = [hex_color[x:x+2] for x in [1, 3, 5]]
...         new_rgb_int = [int(hex_value, 16) + brightness_offset for hex_value in rgb_hex]
...         new_rgb_int = [min([255, max([0, i])]) for i in new_rgb_int] 
...         return "#%02x%02x%02x" % tuple(new_rgb_int)
Lighter colors:
>>> ':'.join(map(color_variant, ("#3b3b3b","#cf6a4c","#99ad6a","#d8ad4c","#597bc5","#a037b0","#71b9f8","#adadad")))
'#636363:#f79274:#c1d592:#ffd574:#81a3ed:#c85fd8:#99e1ff:#d5d5d5'
Original colors:
>>> ':'.join(("#3b3b3b","#cf6a4c","#99ad6a","#d8ad4c","#597bc5","#a037b0","#71b9f8","#adadad"))
'#3b3b3b:#cf6a4c:#99ad6a:#d8ad4c:#597bc5:#a037b0:#71b9f8:#adadad'

Final result using this solution: http://django-notes.blogspot.com/2012/11/gnome-terminal-color-schemes.html
gconftool --set --type string /apps/gnome-terminal/profiles/Default/foreground_color '#adadad'
gconftool --set --type string /apps/gnome-terminal/profiles/Default/bold_color '#adadad'
gconftool --set --type string /apps/gnome-terminal/profiles/Default/background_color '#151515'
gconftool --set --type string /apps/gnome-terminal/profiles/Default/palette '#3b3b3b:#cf6a4c:#99ad6a:#d8ad4c:#597bc5:#a037b0:#71b9f8:#adadad:#636363:#f79274:#c1d592:#ffd574:#81a3ed:#c85fd8:#99e1ff:#d5d5d5'

Sep 6, 2012

Ubuntu terminal shortcuts

CTRL + S - freezes the screen and stops any display on the screen from continuing (equivalent to a no-scroll key) (sometimes takes a moment to work)
CTRL + Q - un-freezes the screen and lets screen display continue
CTRL + \ - same as CTRL - C but stronger (used when terminal doesn't respond)
CTRL + L - clear display

Movement
line: CTRL+ A / CTRL + E
character: CTRL + B / CTRL + F

Search
start: CTRL+ R
cancel: CTRL+ G

Edit
Copy / Paste
CTRL + SHIFT + C / CTRL + SHIFT + V
Change Case
capitalize word: ALT + C
lowercase / uppercase word: ALT + L / ALT + U
Transpose
characters: CTRL+ T
words: ESC + T
Undo
CTRL + _
ALT + R - Undo all changes made to this line

Insert
Line break (\n): CTRL+ V + Return

Delete
character: CTRL + H / CTRL + D
word: CTRL+W / ALT + D
line: CTRL + U / CTRL + K

Auto Completion
command + Tab + Tab
show all possible completions: ALT + ?
insert all possible completions: ALT + *
attempt to complete filename: ALT + \
yank last argument of previous command: ALT + .
repeats the last argument of the previous command: command !$

Clear a mistyped invisible password on a terminal
CTRL + U

http://www.gnu.org/software/bash/manual/bashref.html#Bindable-Readline-Commands

stty -a
http://linux.die.net/man/1/stty

reset

Apr 26, 2012

Linux - Командная строка

Командная строка

Разделение команд

&& - вторая команда будет выполнена только в том случае, если код завершения первой команды будет равен 0.
|| - вторая команда будет выполнена только в том случае, если код завершения первой команды будет отличен от нуля.

История команд

!string - Последняя введенная команда, начинающаяся на string
!?string? - Последняя введенная команда, содержащая строку string

Текстовые потоки и фильтры

Cat, tac

$ cat text1
1
2
в обратном порядке:
$ tac text1
2
1
номера строк (то же что и nl):
cat -n text1
1  1
2  2

Split

по 1 строке
$ split -l 1 text1 lines1_

$ ls lines1_*
lines1_aa  lines1_ab

$ cat lines1_aa
1

$ cat lines1_ab
2
по 2 байта
$ split -b 2 text1 bytes2_

$ ls bytes2_*
bytes2_aa  bytes2_ab

$ cat bytes2_a*
1
2

Sed

$ sed 's/1/555/g' text1
555
2

Управление файлами и директориями

Сортировка вывода

ls -t отсортирует файлы по времени их модификации
ls -lS сформирует подробный список файлов, отсортированных по размеру
-r - сортировка в обратном порядке.

Потоки, программные каналы и перенаправления

Перенаправление вывода

$ ll text1 blablabla >stdout.log 2>stderr.log
Добавляется к содержимому
$ ll text1 blablabla >>stdout.log 2>>stderr.log
Перенаправление двух потоков в один файл
$ ll text1 text3 >output 2>&1
Игнорирование стандартного потока ошибок посредством использования /dev/null
$ ll text1 text3  2>/dev/null

Перенаправление ввода

$ sort -r < text1
2
1
$ sort -r <<END
>5
>6
>END
6
5
- (дефис) - аргумент многих команд, который означает, что входные данные следует принимать со стандартного устройства ввода, а не из файла:
$ bunzip2 -c somefile.tar.bz2 | tar -xvf -
{} - указывает место подстановки
\;, ';' или ";" - команда завершается точкой с запятой, которая представляется в виде escape-последовательности

$ find . -name "*1" -exec grep "1" {} \;
1
1
Здесь не хватает имен файлов, поскольку find вызывает grep один раз для каждого файла, а grep, будучи умной командой, знает о том, что если ей было передано имя лишь одного файла, то нет необходимости сообщать вам о том, что это был за файл.

В этой ситуации мы могли бы воспользоваться командой xargs, однако мы уже знаем о проблеме с файлами, имена которых содержат пробелы. Также мы упоминали тот факт, что команда find может генерировать список имен с пустыми разделителями, благодаря опции -print0. Современные версии команды find могут разделяться не точкой с запятой, а знаком +, благодаря чему, за один вызов команды find можно передать максимально возможное число имен, так же, как и в случае использования xargs
$ find . -name "*1" -print0 |xargs -0 grep "1"
./text 1:1 apple
./text1:1 apple

$ find . -name "*1" -exec grep "1" {} +
./text 1:1 apple
./text1:1 apple

Разделение вывода

Команда tee используется в конвейере, а ее аргументом является имя файла (или имена нескольких файлов), в который будет передаваться стандартный вывод. Опция -a позволяет не замещать старое содержимое файла новым содержимым, а добавлять данные в конец файла. Как уже говорилось при рассмотрении конвейеризации, если вы хотите сохранить как стандартный вывод, так и поток ошибок, то необходимо перенаправлять поток stderr в поток stdout прежде, чем передавать данные на вход команде tee. Для сохранения вывода в два файла, f1 и f2.
$ ls text[1-3]|tee f1 f2
text1
text2
text3

$ cat f1
text1
text2
text3

$ cat f2
text1
text2
text3

Управление приоритетными и фоновыми заданиями

http://www.ibm.com/developerworks/ru/library/l-lpic1-v3-103-5/index.html

Использование &
(while sleep 2; do date;done)&
Ожидание потока stdin:
(date; cat - > bginput.txt;date)&
Использование nohup и списка команд в сценарии:
$ echo "while sleep 30; do date;done">pmc.sh 
$ nohup pmc.sh >mynohup.out 2>&1 &

Мониторинг процессов

$ jobs -p
3878
5485
5487

$ ps (jobs -p)
  PID TTY      STAT   TIME COMMAND
 3878 pts/1    S      0:06 xclock -d -update 1
 5485 pts/1    S      0:00 sh pmc.sh
 5487 pts/1    S      0:00 bash pmc.sh

http://www.ibm.com/developerworks/ru/library/l-lpic1-v3-101-3/

Jun 29, 2011

Hg or git branch in bash prompt

in ~/.bashrc (Ubuntu 12.04)
hg_branch() {
    hg branch 2> /dev/null | \
        awk -v "clrp=$txtpur" -v "clrr=$txtrst" \
            '{ print clrp "@hg:" $1 clrr}'
}
hg_dirty() {
    [ $(hg status 2> /dev/null | wc -l) != 0 ] && \
        echo -e "${txtred}*${txtrst}"
}

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\W$(hg_branch)$(hg_dirty)\$ '
fi
then your prompt will looks like:
someproject$ vi /home/alexey/.bashrc  # make changes above
someproject$ source /home/alexey/.bashrc 
someproject@hg:liveserver$  # liveserver is current brunch
someproject@hg:liveserver$ hg branch
liveserver
someproject@hg:liveserver$ touch blabla
someproject@hg:liveserver*$  # asterisk indicates that VCS has changes
someproject@hg:liveserver*$ hg st
? blabla
Also you can do the same for git:
git_branch() {
    git branch --no-color 2> /dev/null | grep "*" |\
        awk -v "clrp=$txtpur" -v "clrr=$txtrst" \
            '{ print clrp "@git:" $2 clrr}'
}
git_dirty() {
    [ $(git status --short 2> /dev/null | wc -l) != 0 ] && \
        echo -e "${txtred}*${txtrst}"
}

Jun 22, 2011

Изменение размеров всех фото в папке

#!/bin/bash
for f in *.JPG
do
  NEWNAME=`basename ${f} .JPG`_OK.jpg
  echo $NEWNAME
  convert -resize '1024!x768' $f $NEWNAME
done

Jun 20, 2011

Media

Videos

ffmpeg -i input.mpg -ar 22050 -ab 64 -f flv -s 320x240 -r 29.970 -b 1000k -y output.flv

-ar -- is the Audio sample rate ie, 11050, 22050, 44144, and 48000
-ab -- is the Audio Bitrate ie, 64Kbits, 128Kbits, 384Kbtis, etc.
-r ---- is the Frame Rate or fps of the finished video, ie 24, 25, 29.970 etc.
-b ---- is the Bitrate you want to set the flv video to ie, 360k, 1000k etc.

# better
mencoder input.mpeg -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -vf scale=360:240 -o output.avi

# worse
ffmpeg -i input.avi -b 1000 -s 640x480 -vcodec mpeg4 -r 30000/1001 output.avi

# or
ffmpeg -i M2U00009.MPG  -ar 44100 -ab 128k -s 720:480 -padtop 46 -padbottom 50 -padcolor 000000 -ss 00:00:40 -t 00:02:55  -f mp4 grok3.avi

# for android
https://help.ubuntu.com/community/AndroidVideoEncoding

Images

convert -resize '320x240!' 002.jpg thmb_002.jpg

Screenshot

sudo apt-get install scrot
scrot
# or
sleep 10 && scrot
# or
scrot -e 'mv $f /your/pictures'

MySQL

# dump
mysqldump db_name -uroot -p > ffff.sql
mysql db_name -uroot -p < ffff.sql 

# drop all tables
mysql -BNe "show tables" db_name | awk '{print "drop table " $1 ";"}' | mysql db_name