We write a sh script. Writing scripts in Bash. Variables in scripts

In the community of system administrators and ordinary Linux users, the practice of writing Bash scripts is often famous in order to facilitate and simplify the execution of specific goals in the Linux operating system. In this article we will look at writing scripts in Bash, look at the basic operators, as well as how they work, so to speak, Bash scripts from scratch. Simply put, you once wrote the order of events that need to be done, wrote down the data, and so on, and then easily and simply write a single small command and all procedures are carried out as necessary.

It is possible to go even further and schedule the automatic execution of a script. If you are already a more experienced user, then, most likely, you quite often accomplish various goals through the terminal. This is just an example and there are a lot of such actions, even taking backup and uploading copied files to a remote server. There are often tasks for which you need to run several commands in turn, for example, to update the system, you must first update the repositories, and only then download new versions of packages.

This is a command shell where you have the opportunity to issue different commands that will begin to carry out various work at high speed and fruitfully. Absolutely all the power of the Linux OS is in the use of the terminal. Therefore, in order not to type the same commands several times, you can use scripts. This is very convenient, you simply combine several commands that have some effect, and then execute them with the same command or even using a shortcut. For the Linux operating system, many scripts have been created that are executed in various command shells. Well, in principle, you obviously already understand this.

The operating system considers as executable only those files that are assigned the executability characteristic. And the interpreter pronounces line by line in a row and executes all the directives that are present in the file. But if the executability characteristic is set for them, then a specialized computer program is used to launch them - an interpreter, in particular, the bash shell. We can run it like any other program using a terminal server, or we can execute a shell and tell it which file to execute.

In this case, you don't even need an executability flag. Instead, file start signatures and special flags are used. We have several different methods to enable script in Linux OS. Linux OS practically does not use a file extension to determine its type at the system level. File managers can do this, but not always. The operating system considers as executable only those files that are assigned the executability characteristic. These are ordinary files that contain text.

Linux Bash Scripts for Dummies

The bash construct can be described in 7 obligations of a similar type: “calling the command interpreter - the body of the bash script - the end of the script.” Scripts are written with the support of various text editors, and they are stored as text computer data. But, to make it more convenient, I store them together with the “*.sh” extension. But let's look at all this with the example of a specific goal. There is a use that needs to be launched with a fairly large set of characteristics. You will need to start often, and you are too lazy to enter these characteristics every time. To be more specific, let’s see what this effect looks like:

/home/Admin/soft/sgconf/sgconf -s 10.10.10.1 -p 5555 -a Admin -w 112233 -u user -c 100

For this script, let's use the bash interpreter. The primary process you and I need is to call the interpreter. Open a text editor and write code.

Let's add this operation taking into account the entered variables:

/home/Admin/soft/sgconf/sgconf -s 10.10.10.1 -p 5555 -a Admin -w 112233 -u $user -c $cash

The text that we will enter into the logs will be like this: text=”The balance of the user “user” has been replenished with “cash” rubles in time”

The text argument varies depending on the user, cash and time variables

if [ -e /home/Admin/scripts/sgconf/sgconf.log] then echo text >> /home/Admin/scripts/sgconf/sgconf.log else echo text > /home/Admin/scripts/sgconf/sgconf.logfi

Now, when we need to deposit money to someone, we run the script with the command “sh sgconf.sh”, enter the name of the payer and the payment amount. No long lines, no headaches with constantly entering the same values.

Create a bash script in Linux OS

To write a simple script in bash, we need to perform the following ordinary procedures. Let's create a meaningless file on the Linux command line (we call it firstscript for example) and open it for editing in our favorite text editor (vi/vim, nano, gedit, and so on). To develop a script you will not need a lot of effort, but to sketch out a script (program), you will need to study various auxiliary literature. We will describe the basics of writing scripts, so let’s get started, but if you don’t know what a terminal is and how to use it, then this is the place for you. At the very start, in order to write bash, we need to create a directory for our scripts and a file where we will write everything, for this we open the terminal and create a directory.

Switch to the newly created directory

And create a file

sudo gedit script.sh

In my example, I will create a system update script and write it to this file. We will open the text editor gedit, I like vim more, but it won’t be generally accepted among you, so I’m showing it on the standard one.

sudo apt update;sudo apt full-upgrade;

Make the script file executable (if it is not already so). Running sh scripts from the command line is easy. Run bash script linux.

chmod +x script.sh

We run the script by simply specifying the path to it:

path/to/script.sh

If the script is in the current directory, then you need to specify ./ before the script file name:

Sometimes you need superuser rights to run a script, then just write the sudo command before the script:

sudo./script.shsudo path/to/script.sh

You can, of course, start the script by directly specifying the interpreter: sh, bash and others:

bash script.shsh path/to/script.sh

As you can see, starting a sh script in Linux is a fairly common task, even if you are not yet very familiar with the terminal. There are really a lot of scripts and you may need to run some of them. In this guide, we looked at useful Linux bash scripts that you can use when using the Linux OS. In this article, we looked at useful Linux bash scripts that you can use when working with the system. Some of them consist of several lines, a few are placed in one line. There are both minor snippets that you can use in your scripts, as well as full-fledged dialog scripts for working with them through the console.

The command line and the incredible things you can do with it are the hallmark of UNIX and all its successors. And where there is a command line, there are scripts. And today... no, we will not learn to write scripts, we will look at the most useful of them, those that you can use daily to solve a wide range of problems, from weather reports and a web server in one line to a bot for Twitter in ten lines and a script to automatically launch any torrent client.

Let me make a reservation right away that I am not at all a follower of shamanism and in no way urge you to sit in a green and black console and type a bunch of letters in order to perform actions for which in the graphical interface you just need to hover the mouse over the desired element. However, I am convinced that for solving many problems the console and scripts are much better than the graphical interface and therefore cannot be neglected. Moreover, any DE allows you to create an icon for the script, so you don’t even need to open the console to run it.

Simple examples

So, without further ranting, let’s get straight to the examples:

$ curl ifconfig.co

This simple command will show you the external IP - ideal if you access the Network through a router. All it does is simply contact the ifconfig.co server, which returns the IP back in one line instead of a full web page.

And yes, this is not a script at all, it’s just a command, but to turn a command into a script, just put it in a text file and add the so-called shebang as the first line, that is, the symbols #!, followed by the name of the command interpreter:

$ chmod +x ~/bin/myip.sh

Now it can be called from the command line with the command myip.sh.

#!/bin/sh curl -4 wttr.in/Moscow

This script allows you to get a weather report for four days. The principle here is the same as in the case of ifconfig.co.

Weather report in the console #!/bin/sh dig +short txt $1.wp.dg.cx

And this way you can get a brief description of something on Wikipedia, using a DNS query instead of contacting a web server. By the way, it’s also very easy to create a web server via the command line:

#!/bin/sh while (nc -l 80< file.html >:) ; do: ; done

This script is based on the netcat (nc) utility, which is called the Swiss army knife of network operations. The script starts a loop that executes the nc command, which listens on port 80 and responds to the request with file.html, sending the passed request to nowhere (the symbol means noop, that is, an empty operation).

Using simple scripts and commands, you can easily listen to Internet radio:

#!/bin/sh mpv --volume=50 -playlist ~/16bit.fm_128.m3u

Naturally, the playlist in M3U format must be downloaded in advance from the radio station’s website. By the way, if you run MPlayer with the argument --input-ipc-server=/tmp/mpvsocket, it can be controlled by writing commands to a file. For example, adjust the volume:

Echo "volume +10" | socat - /tmp/mpvsocket

Create two scripts: one to start, the other to stop the radio (with the line killall mpv), hang them on your desktop and configure the DE hotkeys to control playback. Voila, you have a ready-made player for Internet radio, which you can launch by simply clicking on the icon on your desktop. And it will hardly consume memory or occupy the tray.

But let's take a break from network operations and return to local affairs.

#!/bin/sh tar -czf "../$(PWD##*/).tar.gz" .

This is one of my favorite scripts. It creates a tar.gz archive of the current directory. Particularly noteworthy here is the $(PWD##*/) construction, which takes the full path to the current directory (the $PWD variable) and removes the first part from it up to the last slash, thus leaving only the name of the directory itself. Next, the extension tar.gz is added to it. You can read more about such constructs in man bash.

#!/bin/sh while true; do inotifywait -r -e MODIFY DIRECTORY && YOUR_COMMAND done

And this is a script that runs a command in response to changes in files in the directory. It can be used for many different purposes, such as automatically turning on the player when saving an MP3 file. Or simply display a notification on the desktop using notify-send as a command:

Notify-send "File changed"

Desktop

Since we're talking about the desktop, let's continue. Like the console, it can also be scripted. For example, here is a script that downloads random wallpapers published on the wallpaper reddit channel:

Continuation is available only to members

Option 1. Join the “site” community to read all materials on the site

Membership in the community within the specified period will give you access to ALL Hacker materials, increase your personal cumulative discount and allow you to accumulate a professional Xakep Score rating!

For writing a simple bash script, we need to perform the following simple steps:

How it all works:

The first line of our script #!/bin/bash is essential for our script to execute successfully.

second line mkdir testdir creates the testdir directory

the third line cd testdir allows you to go to the created directory testdir

team touch in the next line touch file1 file2 file3 creates three files

and the last command in the line of our script, ls -al, allows you to display the contents of the current directory, in which, thanks to the previous line, three empty files have appeared.

As we see, in our simple script all commands start on a new line. Each line, when running the script, sequentially performs its work, performing certain actions.

If you daily execute a chain of any identical commands (with constant parameters) in Linux, then perhaps it makes sense for you to write the same simple bash script, which will allow you to save your time and automate your work.

Writing scripts in Linux (learning with examples)

———————————————————————————-

1. Introduction

What you need to write scripts
Knowledge of command line tools and their required options.
Basic knowledge of English at primary school level will not hurt.

Why are scripts needed?
Firstly, administering a Linux server to one degree or another comes down to systematically executing the same commands. Moreover, it is not necessary that these commands be carried out by a person. They can be programmed to be executed by a machine.
Secondly, even just performing a regular task, which (suddenly) amounts to 20-1000... monotonous operations is MUCH easier to implement in a script.

What is a script
A script is a set of instructions that a computer must execute in a certain order and at a certain time. Instructions can be either internal shell commands (cycles, conditions, processing text information, working with environment variables, etc.), or any program that we execute in the console with the necessary parameters.

How to write a script
In our case, the script will be a text file with execution attributes. If a script file begins with the sequence #!, which in the UNIX world is called sha-bang, then this tells the system which interpreter to use to execute the script. If this is difficult to understand, then just remember that we will start writing all scripts with the line #!/bin/bash or #!/bin/sh, and then the commands and comments for them will follow.

Parting words
I sincerely advise you to write as many comments as possible on almost every line in the script. Time will pass and you will need to change or modernize the script you once wrote. If you don’t remember or don’t understand what is written in the script, then it becomes difficult to change it; it’s easier to write from scratch.

What scripts might we need:

    setting firewall rules when the system boots.
    performing backup of settings and data.
    adding mailboxes to the mail server (more precisely to the mysql database)
    launching at a certain time (preferably every night) a program that scans the proxy server logs and produces a convenient web report on the amount of downloaded traffic.
    sending us information by email that someone has accessed our server via ssh, connection time and client address.

About the method of writing scripts
We create a text file, edit it, set execution rights, run it, look for errors, correct it, run it, look for errors...
When everything is polished and working correctly, we put it in autoload or in the scheduler for a certain time.

———————————————————————————-

2. Learning to write scripts in the internal BASH language
original: https://www.linuxconfig.org/Bash_scripting_Tutorial

This tutorial assumes no prior knowledge of how to write scripts using the internal Bash language. With the help of this guide, you will soon discover that writing scripts is a very simple task. Let's start our tutorial with a simple script that prints the string "Hello World!" (translated from English - Hello everyone!)

1. Scenario “Hello everyone”
Here's your first bash script example:

#!/bin/bash
echo "Hello World"

Let's go to the directory containing our hello_world.sh file and make it executable:

Code: Select all $ chmod +x hello_world.sh

Running the script for execution

Code: Select all $ ./hello_world.sh

2. Simple archiving bash script

#!/bin/bash
tar -czf myhome_directory.tar.gz /home/user

Code: Select all $ ./backup.sh

$ du -sh myhome_directory.tar.gz
41M myhome_directory.tar.gz

3. Working with variables
In this example, we declare a simple variable and display it on the screen using the echo command

#!/bin/bash
STRING=”HELLO WORLD!!!”
echo $STRING

Code: Select all $ ./hello_world.sh
HELLO WORLD!!!

Our archiving script with variables:

#!/bin/bash
OF=myhome_directory_$(date +%Y%m%d).tar.gz
IF=/home/user
tar -czf $OF $IF

Code: Select all $ ./backup.sh
tar: Removing leading "\" from member names
$ du -sh *tar.gz
41M myhome_directory_20100123.tar.gz

3.1 Global and local variables

#!/bin/bash
# Declare a global variable
# Such a variable can be used anywhere in this script
VAR="global variable"
function bash(
# Declare a local variable
# Such a variable is only valid for the function in which it was declared
local VAR="local variable"
echo $VAR
}
echo $VAR
bash
# Note that the global variable has not changed
echo $VAR

Code: Select all $ ./variables.sh
global variable
local variable
global variable

4. Pass arguments to the script

#!/bin/bash
# Use predefined variables to access arguments
# Print arguments to screen
echo $1 $2 $3 ‘ -> echo $1 $2 $3’

#We can also access arguments through a special array args=("$@")
# Print arguments to screen
echo $(args) $(args) $(args) ‘ -> args=(“$@”); echo $(args) $(args) $(args)’

# Use $@ to print all arguments at once
echo $@ ‘ -> echo $@’

Use the $# variable to display the number of arguments passed to the script
echo Number of arguments passed: $# ‘ -> echo Number of arguments passed: $#’

Code: Select all $ ./arguments.sh Bash Scripting Tutorial
Bash Scripting Tutorial -> echo $1 $2 $3
Bash Scripting Tutorial -> args=("$@"); echo $(args) $(args) $(args)
Bash Scripting Tutorial -> echo $@
Number of arguments passed: 3 -> echo Number of arguments passed: $#

5. Executing shell commands in a script

#!/bin/bash
# use backquotes " ` ` " to execute a shell command
echo `uname -o`
# now let's try without quotes
echo uname -o

Code: Select all $ uname -o
GNU/Linux
$ ./bash_backtricks.sh
GNU/Linux
uname -o

As you can see, in the second case the command itself was displayed, and not the result of its execution

6. Reading user input (interactivity)

#!/bin/bash
echo -e "Hi, please type the word: \c "
read word
echo "The word you entered is: $word"
echo -e “Can you please enter two words? »
read word1 word2
echo "Here is your input: \"$word1\" \"$word2\""
echo -e “How do you feel about bash scripting? »
# read command now stores a reply into the default build-in variable $REPLY
read
echo “You said $REPLY, I’m glad to hear that! »
echo -e “What are your favorite colors? »
# -a makes read command to read into an array
read -a colors
echo “My favorite colors are also $(colours), $(colours) and $(colours):-)”

Code: Select all $ ./read.sh
Hi, please type the word: something
The word you entered is: something
Can you please enter two words?
Debian Linux
Here is your input: "Debian" "Linux"
How do you feel about bash scripting?
good
You said good, I"m glad to hear that!
What are your favorite colors?
blue green black
My favorite colors are also blue, green and black:-)

7. Using a trap

#!/bin/bash
# declare a trap
trap bashtrap INT
# clear the screen
clear;
# The hook function is executed when the user presses CTRL-C:
# The screen will display => Executing bash trap subrutine !
# but the script will continue to run
bashtrap()
{
echo "CTRL+C Detected !…executing bash trap !"
}
# the script will count up to 10
for a in `seq 1 10`; do
echo "$a/10 to Exit."
sleep 1;
done
echo "Exit Bash Trap Example!!!"

Code: Select all $ ./trap.sh
1/10
2/10
3/10
4/10
5/10
6/10

7/10
8/10
9/10
CTRL+C Detected !...executing bash trap !
10/10
Exit Bash Trap Example!!!

As you can see, the Ctrl-C key combination did not stop the execution of the script.

8. Arrays
8.1 Declaring a simple array

#!/bin/bash
# Declare a simple array with 4 elements
ARRAY=('Debian Linux' 'Redhat Linux' Ubuntu Linux)
# Get the number of elements in the array
ELEMENTS=$(#ARRAY[@])

# loop through each element of the array
for ((i=0;i<$ELEMENTS;i++)); do
echo $(ARRAY[$(i)])
done

Code: Select all $./arrays.sh
Debian Linux
Redhat Linux
Ubuntu
Linux

8.2 Filling the array with values ​​from the file

#!/bin/bash
# Declare an array
declare -a ARRAY
# exec command # stdin (usually the keyboard) will be derived from this file. This makes it possible to read
# the contents of the file, line by line, and parse each line entered using sed and/or awk.
exec 10 let count=0

while read LINE<&10; do

ARRAY[$count]=$LINE
((count++))
done

echo Number of elements: $(#ARRAY[@])
# Print array values
echo $(ARRAY[@])
# close the file
exec 10>&-

Code: Select all $ cat bash.txt
Debian Linux
Redhat Linux
Ubuntu
Linux
$ ./arrays.sh
Number of elements: 4
Debian Linux Redhat Linux Ubuntu Linux

9. If-then-else conditions
9.1. Simple use of "if-else" conditions
Pay attention to the spaces in the square brackets, without which the condition will not work.

#!/bin/bash
directory="./BashScripting"

# check the presence of a directory
if [ -d $directory ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fi

Code: Select all $ ./if_else.sh
Directory does not exist
$ mkdir BashScripting
$ ./if_else.sh
Directory exists

9.2 Nested if-else conditions

#!/bin/bash
# Declare a variable with the value 4
choice=4
# Display
echo "1. Bash"
echo "2. Scripting"
echo "3. Tutorial"

# Execute while the variable is equal to four
# Looping
while [ $choice -eq 4 ]; do

# read user input
read choice
# nested if-else condition
if [ $choice -eq 1 ] ; then

echo "You have chosen word: Bash"

if [ $choice -eq 2 ] ; then
echo “You have chosen word: Scripting”
else

if [ $choice -eq 3 ] ; then
echo “You have chosen word: Tutorial”
else
echo "Please make a choice between 1-3 !"
echo "1. Bash"
echo "2. Scripting"
echo "3. Tutorial"
echo -n “Please choose a word? »
choice=4
fi
fi
fi
done

Code: Select all $ ./nested.sh
1. Bash
2. Scripting
3. Tutorial

5

1. Bash
2. Scripting
3. Tutorial
Please choose a word?
4
Please make a choice between 1-3 !
1. Bash
2. Scripting
3. Tutorial
Please choose a word?
3
You have chosen word: Tutorial

Thus, the body of the “while” loop is executed first, because the choice variable is initially equal to four. Then we read the user input into it, and if the input is not equal to 1,2 or 3, then we make our variable equal to 4 again, and therefore the body of the loop is repeated (you must enter 1,2 or 3 again).

10. Comparisons
10.1 Arithmetic comparisons

Lt<
-gt>
-le<=
-ge >=
-eq ==
-ne !=

#!/bin/bash

NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values ​​are equal"
else
echo "Values ​​are NOT equal"
fi

Code: Select all $ ./equals.sh
Both Values ​​are equal

#!/bin/bash
# Declare variables with integer values
NUM1=2
NUM2=3
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values ​​are equal"
else
echo "Values ​​are NOT equal"
fi

Code: Select all $ ./equals.sh
Values ​​are NOT equal

#!/bin/bash
# Declare variables with integer values
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values ​​are equal"
elif [ $NUM1 -gt $NUM2 ]; then
echo "$NUM1 is greater then $NUM2"
else
echo "$NUM2 is greater then $NUM1"
fi

Code: Select all $ ./equals.sh
2 is greater then 1

10.2 Character-text comparisons

The same
!= not the same
< меньще чем
> more than
-n s1 variable s1 is not empty
-z s1 variable s1 is empty

#!/bin/bash

S1="Bash"

S2="Scripting"
if [ $S1 = $S2 ]; then

else
echo "Strings are NOT equal"
fi

Code: Select all $ ./statement.sh
Strings are NOT equal

#!/bin/bash
# Declare the character variable S1
S1="Bash"
# Declare the character variable S2
S2="Bash"
if [ $S1 = $S2 ]; then
echo "Both Strings are equal"
else
echo "Strings are NOT equal"
fi

Code: Select all $ ./statement.sh
Both Strings are equal

11. Checking files

B filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check if file is executable

#!/bin/bash
file="./file"
if [ -e $file ]; then
echo "File exists"
else
echo "File does not exist"
fi

Code: Select all $ ls
file.sh
$./file.sh
File does not exist
$ touch file
$ls
file file.sh
$./file.sh
File exists

Similarly, for example, we can use "while" loops to check if the file does not exist. This script will sleep until the file exists. Note the Bash negator "!" which negates (inverts) the -e option.

12. Cycles
12.1. For loop

#!/bin/bash
# for loop
for f in $(ls /var/); do
echo $f
done

Running a for loop from the bash command line:

Code: Select all $ for f in $(ls /var/); do echo $f; done Code: Select all $ for f in $(ls /var/); do echo $f; done
backups
cache
crash
games
lib
local
lock
log
mail
opt
run
spool
tmp
www

12.2. While loop

#!/bin/bash
COUNT=6
# while loop
while [ $COUNT -gt 0 ]; do

let COUNT=COUNT-1
done

Code: Select all $ ./while_loop.sh
Value of count is: 6
Value of count is: 5
Value of count is: 4
Value of count is: 3
Value of count is: 2
Value of count is: 1

12.3. Until loop

#!/bin/bash
COUNT=0
# until loop
until [ $COUNT -gt 5 ]; do
echo Value of count is: $COUNT
let COUNT=COUNT+1
done

Code: Select all $ ./until_loop.sh
Value of count is: 0
Value of count is: 1
Value of count is: 2
Value of count is: 3
Value of count is: 4
Value of count is: 5

12.4. Loops with Implicit Conditions
In the following example, the while loop condition is the presence of standard input.
The body of the loop will be executed as long as there is something to redirect from standard output to the read command.

#!/bin/bash
# This script will search for and remove spaces
# in files, replacing them with underscores
DIR="
Controlling a loop with the read command by redirecting output within the loop.
find $DIR -type f | while read file; do
# use the POSIX [:space:] class to find spaces in filenames
if [[ "$file" = *[[:space:]]* ]]; then
# replace spaces with underscores
mv "$file" `echo $file | tr ‘ ‘ ‘_’`
fi;
done

Code: Select all $ ls -1
script.sh
$ touch "file with spaces"
$ls -1
file with spaces
script.sh
$ ./script.sh
$ls -1
file_with_spaces
script.sh

13. Functions

#!/bin/bash
# Functions can be declared in any order
function function_B(
echo Function B.
}
function function_A (
echo $1
}
function function_D(
echo Function D.
}
function function_C(
echo $1
}
# Call functions
# pass the parameter to the function function A
function_A "Function A."
function_B
# pass the parameter to the function function C
function_C "Function C."
function_D

Code: Select all $ ./functions.sh
Function A.
Function B.
Function C.
Function D.

14. Selection operator - Select

#!/bin/bash
PS3=’Choose one word: ‘
#select
select word in "linux" "bash" "scripting" "tutorial"
do
echo "The word you have selected is: $word"
# Abort, otherwise the loop will be endless.
break
done
exit 0

Code: Select all $ ./select.sh
1) linux
2) bash
3) scripting
4) tutorial
Choose one word: 4
The word you have selected is: tutorial

15. Selection operator - Case

#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2)perl"
echo "3) phyton"
echo "4) c++"
echo “5) I don’t know!”
read case;
# simple case-selection structure
# note that in this example $case is just a variable
# and doesn't have to be called that. This is just an example
case $case in
1) echo “You selected bash”;;
2) echo “You selected perl”;;
3) echo “You selected phyton”;;
4) echo “You selected c++”;;
5) exit
esac

Code: Select all $ ./case.sh
What is your preferred programming / scripting language
1) bash
2) perl
3)phyton
4) c++
5) I don't know!
4
You selected c++

———————————————————————————-

More detailed information can be obtained from various sources, for example here
original: https://www.linuxconfig.org/Bash_scripting_Tutorial
https://ruslandh.narod.ru/howto_ru/Bash-Prog-Intro/
https://bug.cf1.ru/2005-03-17/programmin … -book.html

https://ubuntologia.ru/forum/viewtopic.php?f=109&t=2296

The Linux console is a tool that allows you to perform such manipulations that the command line in Windows does not allow you to do; the Linux console is the calling card of UNIX. Today’s material is not about how to write scripts, no, I won’t teach you how, what and why. We will look at a small selection of useful scripts that you can use every day to solve various types of problems, for example, look at the weather for several days in advance, scripts for a web server in one line, writing a bot for Twitter and a script to automatically launch any torrent client.

This material was not written for you to engage in shamanism, in no case do I encourage you to sit in the console and type hundreds of characters to perform some actions that you can perform in the graphical interface only by hovering the mouse over the element you need. But there is one thing, the graphical interface is not always the best solution; often, for solving many problems, the console and scripts cope with the task much better than applications with a graphical interface, and therefore you should not forget about scripts since they solve a lot of routine work better than graphical ones tools. It’s also worth adding that any DE allows you to create an icon for your scripts, by clicking on which you can easily launch them without opening the console.

Let's start with simple examples

The command below will show you your external IP - this is ideal if you access the Network using a router. This command calls the ifconfig.co server, which returns the IP in one line without unnecessary writing that you don't need.

Curl ifconfig.co

Yes, this is not a script, this is a small command, but if you want to turn this command into a script, you just need to put it in a text file, in the end we will get a small bash script:

#!/bin/bash curl ifconfig.co

We save the script in the ~/bin directory and give execution rights:

Chmod +x ~/bin/yourip.sh

Almost ready, you can execute the script from the command line using the command yourip.sh.

We're done with the IP, let's check the weather from the console.

#!/bin/sh curl -4 wttr.in/Kiev

This script allows you to get a weather report for four days, in this case the weather for the city of Kyiv.

#!/bin/sh dig +short txt $1.wp.dg.cx

Above you see an example of how you can get a short description of something on Wikipedia, in our case we use a DNS query instead of contacting the web server. It is also very easy to create a web server via the console:

#!/bin/sh while (nc -l 80< file.html >:) ; do: ; done

The script above is based on the netcat (nc) utility, often called the Swiss army knife, as it allows you to do many tricks for network operations. The script is simple, it starts a loop that executes the nc command, which already listens to port 80 and responds to the request file.html, sending the passed request to nowhere (the symbol means noop, that is, an empty operation).

Using simple scripts and commands, you can listen to Internet radio:

#!/bin/sh mpv --volume=50 -playlist ~/16bit.fm_128.m3u

Of course, before this you need to download the radio playlist in M3U format from the radio station's website. If you launch MPlayer using the argument -input-ipc-server=/tmp/mpvsocket, it can be controlled by writing commands to a file. For example, adjust the volume:

Echo "volume +10" | socat - /tmp/mpvsocket

We create two scripts: the first to start, and the other to stop the radio (in which we will write the line killall mpv), then hang it on the desktop, together setting up the DE hot keys to control playback. And that's it, you have a player with which you can listen to Internet radio.

We got carried away with network operations, let's move on to local ones.

#!/bin/sh tar -czf "../$(PWD##*/).tar.gz" .

This script creates a tar.gz archive for the current directory. Particular attention should be paid to the $(PWD##*/) construction, which takes the entire path to the current directory (the $PWD variable), then removes the first part up to the last slash, leaving only the directory name and adding the tar.gz extension to it. If you want to find out more information on such constructions, you can read by running the man bash command in the console.

#!/bin/sh while true; do inotifywait -r -e MODIFY DIRECTORY && YOUR_COMMAND done

The script above runs a command in response to changes to files in a directory. You can use it for different purposes, as an example for automatically turning on the player when saving MP3. Or, as an example, display a notification on the desktop using the notify-send command:

Notify-send "File changed"

For desktop

Below you will see an example of a script that loads random wallpapers that are published on the wallpaper reddit channel:

#!/bin/bash wget -O - http://www.reddit.com/r/wallpaper |\ grep -Eo "http://i.imgur.com[^&]+jpg" |\ shuf -n 1 |\ xargs wget -O background.jpg feh --bg-fill background.jpg

It all works quite simply. Using the wget utility, the script downloads the page www.reddit.com/r/wallpaper, then passes it to grep, which already looks for links to imgur, and selects a random one using shuf, downloads it using wget and sets it as wallpaper for your desktop, using the feh command (this is a miniature image viewer that must be installed first). You can add this script to a regular text file as I described above, save it in sh format, make it executable, add an icon to it and run it from the desktop by clicking and your wallpaper will change.

#!/bin/sh state=`synclient | grep TouchpadOff | cut -d "=" -f 2` if [ $state = "1" ]; then synclient TouchpadOff=0 else synclient TouchpadOff=1 fi

The above script is used to enable and disable your laptop's touchpad: enable if disabled and vice versa. For correct operation, it uses the synclient utility, which allows you to control touchpads, which are mostly produced by Synaptics, this is 90% possible, even more. After launch, the utility displays a lot of information, including the line TouchpadOff = 1 if it is activated, and TouchpadOff = 2 if it is disabled. The script will read these values ​​and, depending on the state of the touchpad, enable or disable it.

!#/bin/bash mpv tv:// -frames 3 -vo jpeg mv 00000003.jpg photo.jpg rm -f 0000*.jpg

Using the script above, you can take a photo using your webcam. The script uses an mpv video player that records the first three frames captured by the camera into JPEG format files with names 0000000.jpg, 00000002.jpg, 00000003.jpg, etc., after which the third image is renamed into a photo.jpg file, and the rest are deleted. What are three pictures used for? They are only needed so that your camera has time to initialize; if you use the first two pictures, you will usually get a black picture. There are also incidents with positioning, the photo may be upside down; to avoid this, mpv needs to be launched with the -vf flip flag:

Mpv tv:// -frames 3 -vf flip -vo jpeg

You can use the same command to create a security camera that will only take pictures when the user touches the mouse:

#!/bin/bash while true; do sudo cat /dev/input/mouse0 | read -n1 mpv tv:// -frames 3 -vo jpeg mv 00000003.jpg `date +%F-%H-%M`.jpg rm -f 0000*.jpg sleep 10 done

The script above uses an infinite loop, fetching data from the device /dev/input/mouse0. If there is data, it means the mouse has been moved or one of its buttons has been pressed. Then mpv is used to create three snapshots, the third snapshot is given the name of the current date and the first two are deleted.

If you want to record a full-fledged video from a webcam, you can use a similar script as an example:

#!/bin/bash mencoder tv:// -tv driver=v4l2:width=800:height=600:device=/dev/video0:fps=30:outfmt=yuy2:forceaudio:alsa:advice=hw.2, 0 -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=1800 -ffourcc xvid -oac mp3lame -lameopts cbr=128 -o video.avi

As a result, you will receive a file called video.avi in ​​MPEG4 format, bitrate 1800, and an audio file in MP3 format with bitrate 128.

#!/bin/bash ffmpeg -f x11grab -r 25 -s 1366x768 -i:0.0 screencast.mpg

Using the script above, you can record a full screencast. 1366×768 is the desktop resolution, you can customize it to suit you. To take a screenshot of a single window, you can use the import command:

Import screenshot.png

If you run the command above, your mouse cursor icon will change to a cross, using which you can select an area of ​​the screen as you do when taking screenshots using third-party applications or extensions. If you attach this command to one of the hotkeys, you will get an almost ideal system for taking screenshots, and this combination will not eat up your RAM, which significantly gives it a huge advantage.

You can also configure an external monitor using the console:

#!/bin/sh if [ -z "$1" ]; then exit fi if [ $1 == "off" ]; then xrandr --output VGA-0 --off xrandr -s 0 else if [ $1 == "on"]; then xrandr --output LVDS --auto --primary --output VGA-0 --auto --left-of LVDS xrandr --newmode "1920x1080" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync xrandr -- addmode VGA-0 1920x1080 xrandr --output VGA-0 --mode 1920x1080 fi xrandr --dpi 96

This script is based on the fact that the main monitor is named LVDS, and the external monitor is named VGA-0. This is a standard situation for all laptops; if you are not sure, you can check by running the xrandr command: when passing an argument to the script off it disables the external monitor, argument on, in turn, includes it, placing it on the left side of the main one (argument -left-ofLVDS in the first team). The script then creates a new configuration for the monitor with a resolution of 1920 x 1080 and activates it. And finally, the script sets the default DPI value - since when connecting a monitor with a different resolution, it often crashes.

In most cases the commands xrandr -newmode… And xrandr -addmode... are not needed since Xorg will obtain the monitor configuration and resolution using the EDID. Sometimes, however, this does not happen, and the configuration string specified after the argument -newmode, you have to generate it yourself using the cvt tool:

CVT 1920 1080

Using the cvt tool, you can generate custom resolutions that are not supported by the default monitor.

Searching Google from the command line

Let's return again to network services. How to Get Top 10 Search Results in Google? Look at the script below:

#!/bin/bash Q=" " URL="https://www.google.de/search?tbs=li:1&q=" AGENT="Mozilla/4.0" stream=$(curl -A "$AGENT" -skLm 10 "$(GOOG_URL)$(Q//\ /+)" | grep -oP "\/url\?q=.+?&" | sed "s|/url?q=||; s| &||") echo -e "$(stream//\%/\x)"

This script sends a request to Google using curl, replacing spaces in the search string with pluses. Then links pop up in the response HTML

Example with the YouTube service:

#!/bin/bash mpv -fs -quiet `youtube-dl -g "$1"`

The script from the example above plays a video with the ID specified in the argument using an mpv player. You need to install youtube-dl in advance.

Several examples of working with Twitter. Below you will see a script for a full-fledged bot, which accepts a command as input, executes it using the command interpreter and sends the result to the specified user.

#!/bin/bash USER="Your Nickname" while true; do CMD=`echo "/dma +1" | ttytter-script | sed "s/\[.*\]\ //" if [ $CMD != $OLD_CMD ]; then REPL=`$CMD` echo "/dm $USER $(REPL:0:140)" | ttytter -script CMD = $OLD_COMD fi sleep 60 done

The script uses the ttytter console client, reading the last direct message value from the loop, then checking whether this command was executed, if not, it executes it and sends it to the specified user with the USER variable, cutting off up to 140 characters.

For everything to work, you need to install the ttytter utility, run it, then copy the generated link from the console and paste it into the address bar of the browser, go through confirmation, agree, then receive the authentication key, copy and paste it into the console in ttytter. Of course, before all this, it is advisable to add a separate user and log in under his account.

You can use Twitter not only to create a bot, but also to monitor your machine. The script below sends a message to the feed with information about the state of the machine (host name, uptime, load, free memory and CPU load):

#!/bin/bash HOST=`hostname -s` UP=`uptime | cut -d" " -f4,5 | cut -d"," -f1` LOAD=`uptime | cut -d":" -f5,6` MEM=`ps aux | awk "( sum += $4 ); END ( print sum )"` CPU=`ps aux | awk "( sum += $3 ); END ( print sum )"` tweet="Host: $(HOST), uptime: $(UP), cpu: $(CPU)%, memory: $(MEM)%, loadavg $(LOAD)" if [ $(echo "$(tweet)" | wc -c) -gt 140 ]; then echo "FATAL: The tweet is longer than 140 characters!" exit 1 fi echo $tweet | ttytter-script

Finally, look at the script below, this script is used to start and stop the torrent client while your PC is idle:

#!/bin/bash IDLE=600000 STOPCMD="transmission-remote -S" STARTCMD="transmission-remote -s" STOPPED="yes" while true; do if [ `xprintidle` -gt $IDLE ]; then if [ $STOPPED = "yes" ]; then $STARTCMD STOPPED="no" fi else if [ $STOPPED = "no" ]; then $STOPCMD STOPPED="yes" fi fi sleep 60 done

Every minute the script goes into an infinite loop and checks how much time in milliseconds has passed since the user performed the last action (xprintidle is used for these purposes). If 600,000 ms (ten minutes) have passed, the script executes the command specified in the STARTCMD variable. Otherwise, the STOPCMD command is executed, but only if STARTCMD was executed before it. To explain it in simple terms, you do nothing at the computer for ten minutes, then STARTCMD is launched, in our case this is the command that starts all downloads in Transmission, if not, all downloads are suspended. Don't like the Transmission client? We use commands for Deluge, see below:

STOPCMD="deluge-console pause \*" STARTCMD="deluge-console resume \*"

Conclusion