Как стать автором
Обновить

Шпаргалка по bash

Уровень сложностиПростой

Эта статья написана больше для себя, чтобы не искать наработки в разных местах. Если кому-то будет полезно, буду рада :)

Перемещение директории

#! /bin/bash

#check if dir $1 exists
if [ ! -d "$1" ]
then
	echo "$1 doesn't exist"
	exit 1
fi

#check if dir $2 exists
if [ ! -d "$2" ]
then
	echo "$2 doesn't exist"
	exit 1
fi

#remove $1 only if copying was success
if cp -r "$1" "$2" && rm -r "$1"
then
	echo "Dir $1 was moved to dir $2 successfully"
	exit 0
else
	echo "Something wents wrong"
	exit 1
fi

Переименование файла

#! /bin/bash

#check input data before start proccess
if [ $# -ne 2 ]
then
	echo "2 args needs, the file you want to rename and the new name of file"
	exit 1
fi

# check if file $1 exists and really is file, not folder
if [ ! -f "$1" ]
then
	echo "File $1 does not exist or it's not a file, maybe a folder, please try again"
	exit 1
fi

# the proccess of renaming and check that everything finished success
if cp "$1" "$2" && rm -f "$1"
then
	echo "Name of file $1 was changed to $2"
	exit 0
else
	echo "Something went wrong!"
	exit 1
fi

Поиск максимального числа

#! /bin/bash

read -p "Please, enter number 1: " num1
read -p "Please, enter number 2: " num2
read -p "Please, enter number 3: " num3

# check if all enetered lines really numbers
if ! [[ $num1 =~ ^[0-9]+$ ]] || ! [[ $num2 =~ ^[0-9]+$ ]] || ! [[ $num3 =~ ^[0-9]+$ ]]
then
	echo "Error! num1, num2 and/or num3 not a number!"
	exit 1
else
	# -gt = >
	if [ "$num1" -gt "$num2" ]
	then
		if [ "$num1" -gt "$num3" ]
		then
			echo "$num1 is maximal number"
		elif [ "$num3" -gt "$num2" ]
		then
			echo "$num3 is maximal number"
		fi
	elif [ "$num2" -gt "$num3" ]
	then
		echo "$num2 is maximal number"
	elif [ "$num3" -gt "$num1" ]
	then
		echo "$num3 is maximal number"
	else
		echo "all of entered numbers are equal: $num1"
	fi
fi

Калькулятор

#! /bin/bash

read -p "Enter the first value: " x
read -p "Enter the second value: " y
read -p "Enter the operator: " oper

if ! [[ $x =~ ^[0-9]+$ ]] || ! [[ $y =~ ^[0-9]+$ ]]; then
	echo "Wrong format! Please use numbers only!"
	exit 1
else
	case $oper in
		"+") echo "$x + $y = " $(("$x" + "$y"));;
		"-") echo "$x - $y = " $(("$x" - "$y"));;
		"*") echo "$x * $y = " $(("$x" \* "$y"));;
		"/") if [[ $y -eq 0 ]]; then
			echo "Impossible to divde on zero!"
		else
			echo "$x / $y = " $(("$x" / "$y"))
		fi;;
		"**") echo "$x ** $y = " $(("$x" ** "$y"));;
		*) echo "Unkonwn operation!"
	esac
fi

Расширенный пинг

#! /bin/bash

HOST_RES=$(host yandex.ru)
PING_RES=$(ping -c4 yandex.ru)
PING_TAIL=$(ping -c4 yandex.ru | tail -n 2)

if [[ $HOST_RES =~ 'yandex.ru has address' ]]; then
	echo "Connection with DNS: SUCCESS"
else
	echo "Something wrong with you internter connection!"
	exit 1
fi

if [[ $PING_RES =~ '0% packet loss' ]]; then
	echo "PING to yandex.ru: SUCCESS"
else

	echo "Something wrong with you internter connection!"
	exit 1
fi

echo "The result of yandex.ru PING:"
echo "$PING_TAIL"

Вывод чётных предсказаний

#! /bin/bash
num=0
while [ $num -lt 10 ]; do
	num=$(expr $num + 1)
	if ! (( $num % 2)); then
		echo $num $(fortune)
	fi
done

Вывод зверушки с предсказанием

#! /bin/bash

while true; do
	echo "Who do you want advice from?"
	cat << options
bunny
tux
daemon
kitty
vader-koala
	
options
	echo
       	read -p "Make your choice: " option
	if [ $option = 'quit' ]; then
		break
	fi
	echo 
	fortune | cowsay -f $option
done

Чтение файла построчно

#! /bin/bash

read -p "Please enter name of reading file: " reading_file
num=1

while read line; do
	echo "Line $num: $line"
	num=$(( $num + 1 ))
done < $reading_file

Создание папок с датой в названии

#! /bin/bash

num=1
until [ $num -eq 8 ]; do
	date=`date +%Y%m%d`
	time=`date +%H%M`
	mkdir ~/tmp/directory-${date}_${time}	
	num=$(( $num + 1 ))
	if [ $num -eq 8 ]; then
		break
	fi
	sleep 7m
done 

Функция возведения в степень чисел

#! /bin/bash

sqrt(){
	echo $1^2 | bc -l
}

for ((i=10; i<=20; i++)); do
	echo "$i^2 = " $(sqrt $i)
done

Постановка задачи в cron

Теги:
Хабы:
Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.