bash and command line Flashcards
redirect the output
something (1)> output.file
something (1)» output.file (append redirection, old content is not erased)
something &> output.file (for both output and errors)
variables in command line
$[var_name]
reading the input
read a >> hello $a = 'hello' read >> hi $REPLY = 'hi' read -p 'enter value: ' q >> enter value: 1 $q = 1
how to make a permanent variable
add to .bash_profile/.bashrc
redirect the error
something 2> output.file
grep
grep searchcontent searchsource
grep -i (case insensitive)
grep -v (excluding)
brace expansion
echo test{1,2,5}
» test1 test2 test5
echo test{1..6}
» test1 test2 test3 test4 test5 test6
permission
r - readable
w - writable
x - executable
-/d{rwx}{rwx}{rwx} = owner-group-other
change permission
chmod [u|g|0]=rwx file
chmod [+|-]rwx file
basic script structure
> > touch hello
nano hello
#! /bin/bash
echo ‘hello there’
> > chmod +x hello
./hello
‘hello there’
if condition
if [ some condition ]; then do something elif [ some other condition ]; then do this else do this instead fi
(non)empty string
-n|-z $var_string
number conditions
- eq ==
- ne !=
- lt <=
- gt >=
file conditions
- e exists
- d is a directory
- f is a regular file
- s not empty
- r is readable
- w is writable
- x is executable
logic conditions
and: -a [ [ cond && cond ] ]
or: -o [ [ cond || cond ] ]
for loop
for i in {range}; do
do something
done
for i in (( i = 0; i < 25; i = i+1 )); do
do something
done
source command
runs the script in the current shell
alias
alias [name]=’command’
unalias [name]
alias # show all aliases
command expansion/substitution
$(command)
parameters in a script
${1-999}
$# - number of parameters
$@ - all parameters
$* - all parameters (note: “$*” counts as one item like a string)
adding a script to the PATH
.profile
PATH=”path_to_script:${PATH}”
export PATH
functions
myfunc(){
}
bc computations
bc -q bc -l (default scale) scale=2 1/3=.33 scale(1.214)=3 sqrt(16)=4 quit
input redirection
command «_space;EOF
command «< ‘string’
calculation script
#! /bin/bash if [ "$1" == "-p" ]; then precision=$2 shift #shifting parameters else precision=3 fi bc << _EOF_ scale=$precision $@ _EOF_
script for reading /etc/passwd
! /bin/bash
FILE=/etc/passwd
read -p “enter the username: “ user_name
info=$(grep $’user_name’ $FILE)
echo $info
old_IFS=$IFS
IFS=$: # internal field separator
if [ -n "$info" ]; then read user pw uid gid full home shell <<< "$info" echo "user: $user" echo "pass: $pw" echo "uid: $uid" echo "gid: $gid" echo "name: $full" echo "home: $home" echo "shell: $shell" else echo "user not found" fi IFS=$old_IFS
wc #word counter
wc -l file (lines)
wc -w file (words)
wc -m file (characters)
strings
strings file (gives out all the strings) strings -n file (gives out strings at least n characters long)
arrays
days=(mon tue wed thu fri sat sun)
days[0]=mon
${!arr[@]} # which indexes are filled
awk
$ awk options program file
$ awk ‘{print $1}’ myfile
$ awk -F: ‘{print $1}’ /etc/passwd
- F fs — позволяет указать символ-разделитель для полей в записи.
- f file — указывает имя файла, из которого нужно прочесть awk-скрипт.
- v var=value — позволяет объявить переменную и задать её значение по умолчанию, которое будет использовать awk.
- mf N — задаёт максимальное число полей для обработки в файле данных.
- mr N — задаёт максимальный размер записи в файле данных.
- W keyword — позволяет задать режим совместимости или уровень выдачи предупреждений awk.
$ echo | awk -v home=$HOME ‘{print “My home is “ home}’
$ awk ‘{if ($1 > 20) print $1}’ testfile
$ awk '{ total = 0 i = 1 while (i < 4) { total += $i i++ } avg = total / 3 print "Average:",avg }' testfile
$ awk '{ total = 0 for (i = 1; i < 4; i++) { total += $i } avg = total / 3 print "Average:",avg }' testfile
$ awk ‘BEGIN{
x = 100 * 100
printf “The result is: %e\n”, x
}’
sed
Утилиту sed называют потоковым текстовым редактором. В интерактивных текстовых редакторах, наподобие nano, с текстами работают, используя клавиатуру, редактируя файлы, добавляя, удаляя или изменяя тексты. Sed позволяет редактировать потоки данных, основываясь на заданных разработчиком наборах правил. Вот как выглядит схема вызова этой команды:
$ sed options file
$ echo “This is a test” | sed ‘s/test/another test/’
В данном случае sed заменяет слово «test» в строке, переданной для обработки, словами «another test». Для оформления правила обработки текста, заключённого в кавычки, используются прямые слэши. В нашем случае применена команда вида s/pattern1/pattern2/. Буква «s» — это сокращение слова «substitute», то есть — перед нами команда замены. Sed, выполняя эту команду, просмотрит переданный текст и заменит найденные в нём фрагменты
Вызовем sed, передав редактору файл с командами и файл для обработки:
$ sed -f mycommands myfile
В некоторых случаях с помощью sed надо обработать лишь какую-то часть текста — некую конкретную строку или группу строк. Для достижения такой цели можно воспользоваться двумя подходами:
Задать ограничение на номера обрабатываемых строк.
Указать фильтр, соответствующие которому строки нужно обработать.
используя команду d, можно удалять строки из текстового потока.
Вызов команды выглядит так:
$ sed ‘3d’ myfile
Если вызвать sed, использовав команду =, утилита выведет номера строк в потоке данных:
$ sed ‘=’ myfile