bash and command line Flashcards

(31 cards)

1
Q

redirect the output

A

something (1)> output.file
something (1)» output.file (append redirection, old content is not erased)
something &> output.file (for both output and errors)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

variables in command line

A

$[var_name]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

reading the input

A
read a
>> hello
$a = 'hello'
read
>> hi
$REPLY = 'hi'
read -p 'enter value: ' q
>> enter value: 1
$q = 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

how to make a permanent variable

A

add to .bash_profile/.bashrc

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

redirect the error

A

something 2> output.file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

grep

A

grep searchcontent searchsource
grep -i (case insensitive)
grep -v (excluding)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

brace expansion

A

echo test{1,2,5}
» test1 test2 test5
echo test{1..6}
» test1 test2 test3 test4 test5 test6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

permission

A

r - readable
w - writable
x - executable

-/d{rwx}{rwx}{rwx} = owner-group-other

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

change permission

A

chmod [u|g|0]=rwx file

chmod [+|-]rwx file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

basic script structure

A

> > touch hello
nano hello
#! /bin/bash
echo ‘hello there’

> > chmod +x hello
./hello
‘hello there’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

if condition

A
if [ some condition ]; then
    do something
elif [ some other condition ]; then
    do this
else
    do this instead
fi
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

(non)empty string

A

-n|-z $var_string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

number conditions

A
  • eq ==
  • ne !=
  • lt <=
  • gt >=
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

file conditions

A
  • e exists
  • d is a directory
  • f is a regular file
  • s not empty
  • r is readable
  • w is writable
  • x is executable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

logic conditions

A

and: -a [ [ cond && cond ] ]
or: -o [ [ cond || cond ] ]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

for loop

A

for i in {range}; do
do something
done

for i in (( i = 0; i < 25; i = i+1 )); do
do something
done

17
Q

source command

A

runs the script in the current shell

18
Q

alias

A

alias [name]=’command’
unalias [name]
alias # show all aliases

19
Q

command expansion/substitution

20
Q

parameters in a script

A

${1-999}
$# - number of parameters
$@ - all parameters
$* - all parameters (note: “$*” counts as one item like a string)

21
Q

adding a script to the PATH

A

.profile
PATH=”path_to_script:${PATH}”
export PATH

22
Q

functions

23
Q

bc computations

A
bc -q bc -l (default scale)
scale=2 1/3=.33
scale(1.214)=3
sqrt(16)=4
quit
24
Q

input redirection

A

command &laquo_space;EOF

command «< ‘string’

25
calculation script
``` #! /bin/bash if [ "$1" == "-p" ]; then precision=$2 shift #shifting parameters else precision=3 fi bc << _EOF_ scale=$precision $@ _EOF_ ```
26
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 ```
27
wc #word counter
wc -l file (lines) wc -w file (words) wc -m file (characters)
28
strings
``` strings file (gives out all the strings) strings -n file (gives out strings at least n characters long) ```
29
arrays
days=(mon tue wed thu fri sat sun) days[0]=mon ${!arr[@]} # which indexes are filled
30
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 }'
31
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