How can I practice UNIX Scripting Bash

Useful scripts

Useful scripts

Here are a few useful scripts that you can use can customize at will. A script (actually in the German script) is most likely known as a screenplay script. In principle, however, it is exactly this. It's a script for command line commands. Commands on the command line are executed like a military command without further checking, provided that it is known and the syntax is correct! Since a complete Linux installation can thus also be made unusable or deleted without further inquiry, the command generator should know the commands that he issues and their effects very precisely! In Linux (and the other Unix-like operating systems) the command line is very powerful. Compared to instructions that someone should implement on the graphical desktop, command line commands are (mostly) independent of the distribution, version and graphical user interface. And so if you have been using Linux for a long time, they are a better tool, if you want to help someone who has not yet familiarized themselves with Linux (and perhaps uses a different distribution or a different desktop than you do).

A couple of helpful commands, so-called Command line commands, can be found on the mini HowTos page.

A script can actually be created with any Linux text editor such as,,,, etc. It is important that you then tell Linux that the file should be executable. This is done with the command and the easiest way is simply with the parameter as executable (English exmark ecuteable).

Linux also needs either the absolute file name or the script must be in an executable directory that can be displayed with. The paths are separated with ':'. Normally the current directory cannot be executed on Linux / Unix, which is why you can then execute the script with.

Example file

kate xxx.sh # => Starts the KDE text editor Kate, which creates the file 'xxx.sh' in the current directory when you exit it after saving. chmod + x xxx.sh # => makes the file 'xxx.sh' executable in the current directory ./xxx.sh # => executes the file 'xxx.sh' in the current directory License: All scripts marked GPL without a version fall under GPL 2.0. See also LugVSWiki: Copyright and notice at the bottom of this page.

Creation of (several) folders / files

Creates the folder "MyFolders" in the current working directory.

mkdir myfolder

Creates the two folders "MeinFolder1" and "MeinFolder2" in the current working directory

mkdir myfolder1 myfolder2

Creates the following folders and sub-folders:
folder
├── A11
│ ├── AU1
│ └── AU2
└── A12
├── AU1
└── AU2

mkdir -p folder / {A11, A12} / {AU1, AU2}

Create folder with consecutive number in the current working directory:

mkdir 202 {0..9}

Creates the folders 2020 to 2029.

BASH script for the colored output of DiskFree

A small script that shows the output of the BASH command DiskFree (df) in a legible form and adapts the color of each line from default (green) to yellow (alarm level) and red (critical alarm level) line by line, depending on the fill level in%. This means that the color shows when a hard disk is running full. At the moment the script doesn't know any arguments, which I might adjust again soon.

#! / bin / bash # # df with some options and colored if Alert levels are exceeded # (c) GPL by Ulf Bartolomäus VERSION = "Version 0.1.1 from 13.02.2021" # 0.1. $ (echo "$ {MyDfUsage} "| grep [[: digit:]])]]; then ## If first row echo -e $ {thick} "$ {MyOutput}" $ {norm} ## Echo in bold elif [$ (($ {MyDfUsage}))) -ge $ {MyDfAlert2}]; then ## If critical level excided echo -e $ {red} "$ {MyOutput}" $ {norm} ## Echo in red elif [$ (($ {MyDfUsage})) -ge $ {MyDfAlert1}]; then ## If alert level excided echo -e $ {yellow} "$ {MyOutput}" $ {norm} ## Echo in yellow else ## default echo -e $ {green} "$ {MyOutput}" $ {norm} ## Echo in green fi done

BASH script: Write JPEG EXIF ​​text

This is a BASH script which, starting from the current directory, searches all subdirectories recursively for a file filter (here * .jpg). The tool exiftran applied. This overwrites the picture comment with the specified text. Attention, the comment there so far is really lost because it will be overwritten. So that there is no rude awakening, a copy of each changed file is made with the ~ created at the end (i.e. from xx.jpg becomes xx.jpg ~). If you are sure that you will not overwrite any comments, you can of course choose the option -b at exiftran omit and overwrite the content. I would not recommend that, but rather delete the backup copies if necessary.

Danger: The command deletes including the current directory, all subdirectories and their files without further request. Therefore, the asterisk (*) and the tilde (~) must always be attached to one another and ideally also be enclosed in quotation marks (") so that they can be combined into a search filter! The asterisk (*) is on the command line Placeholder for all characters in any number of repetitions! To be on the safe side, I've added the parameter that asks again (see also man rm).

The script is started on the command line with the comment text as a parameter, preferably in quotation marks (only if it is in a directory from PATH -> display with echo $ PATH, otherwise the complete path must of course also be given): make_exif-name.sh "© Ulfi".

Alternatively, you can use other tools to read and write EXIF ​​comments. The following commands display the EXIF ​​comment

exiftool -a -u image.jpg | grep Comment convert Bild.jpg -format "% c \ n" info: identify -verbose Bild.jpg | grep comment:

The following commands write the EXIF ​​comment

exiftran -ibp -c "Comment" Bild.jpg convert Bild.jpg -set comment "Comment" BildOut.jpg

Script with the EXIFtran program as an example:

#! / bin / bash # Add a exif-comment to all JPEG-Files from this directory and all subdirectorys # # (c) LUG-VS (GPL) VERSION = "make_exif-name.sh Version 0.0.2 from 23.10.2005 "# # Input: comment text # Output: changed files # # Changes: # 0.0.2: comment as parameter from commandline # 0.0.1: generation # COMMENTSTEXT = $ * JPEGFILEFILTER = *. Jpg # trap is executed if script breaks trap "echo '*** TRAP ***'; exit" ERR # check if command exists else break which exiftran> / dev / null || echo "exiftran not found!" || exit; echo "Write Comment: <" $ {COMMENTSTEXT} ">" # for each file in JPEGFILEFILTER do # exiftran - transform digital camera jpeg images and use the libexif-Library # -i Enable inplace editing of the images. # -b Create a backup file when doing inplace editing. # -p Preserve timestamps (atime + mtime) when doing inplace editing. # -c Set jpeg comment tag to . find. -type f -name "$ {JPEGFILEFILTER}" -exec exiftran -ibp -c "$ {COMMENTSTEXT}" {} \;

BASH script: Show EXIF ​​comment in picture

If you want to write the EXIF ​​comment text in the pictures yourself so that you can always see them when looking at them, there are many options. Some are e.g. in the ImageMagic package and can be used there in a variety of ways. An overview of the ImageMagic possibilities to write text in images can be found here (in English).

In the above script we learned how to write EXIF ​​comments in a picture. In this script we read them out again and write them into the picture itself so that you can always see it.

#! / bin / bash # Write an exif-comment to all JPEG-Files from this directory and all subdirectorys # # (c) LUG-VS (GPL) VERSION = "write-exif-comment.sh Version 0.0.1 from 16.06 .2019 "# # Input: InImage [OutImage] # Output: changed files # # Changes: # 0.0.1: generation # test -e $ 1 || exit -1 FilenameFull = "$ 1" if [$ # -gt 1]; then FilenameSik = "$ 2" else Extension = "$ {FilenameFull ## *.}" FilenameBase = "$ {FilenameFull%. *}" FilenameSik = "$ {FilenameBase} New. $ {Extension}" fi CommentsText = "$ ( convert $ {FilenameFull} -format "% c \ n" info :) "Width = $ (identify -format% w $ {FilenameFull}) High = $ (($ (identify -format% h $ {FilenameFull}) / 10 )) echo "EXIF comment = <$ {CommentsText}> of <$ {FilenameFull}> ($ {Width} x $ {High} $ {FilenameSik})" convert -background '# 0008' -fill white -gravity center -size $ {Width} x $ {High} caption: "$ {CommentsText}" \ $ {FilenameFull} + swap -gravity south -composite $ {FilenameSik}

BASH script: Download of numbered files

Sometimes you want some files with a consecutive number from e.g. 01 to 99 (i.e. with a leading zero) numbered consecutively download or process it differently in a script. But if you insert a bash variable directly, you get 1 instead of 01. In the following script I implemented something like this (I don't want to rule out that there is also a more elegant way).

The script itself is actually quite simple. First some variables are pre-assigned. In the example, e.g. a proxy is set, e.g. to switch an ad blocker or an anonymization service in between. Then it changes to the target directory. Now one starts for-Loop which the variable NO counts up. Within the loop, first the units and tens values ​​are determined with the help of an arithmetic operation. In bash, an arithmetic operation is performed with a $ introduced and enclosed within a double round bracket e.g. $((567 / 10)). This then replaces the calculation with the result, so in the example is $((567 / 10)) by 56 replaced (i.e. an integer or whole number). If the powers of ten are now separated, you can use the download tool as in the example wget be used. This loads the file (if necessary in several attempts) via the proxy into the local directory. When all files have been loaded, the loop is ended and the system switches back to the original directory.

#! / bin / bash # (c) LUG-VS (GPL) # Set Variables export http_proxy = http: //proxy.homenetz.de: 1234 / # Set an Proxy # Change to destination path cd $ {HOME} / MyDestinationPath # Do for every Number from 1 to 99 for ((NR = 1; $ NR <100; NR = $ NR + 1)); do # Calkulate exponents (10 ^ 1 and 10 ^ 0) ZNR = $ (($ {NR} / 10)) ENR = $ (($ {NR} - $ ((10 * $ {ZNR})))) # Echo and download the file with the number and save to an other name echo -e "\ twget --proxy = on -c ftp://tst.de/path/File$ GenealogieZNR}$ GenealogieENR Genealogie.Ext -O File $ {ZNR} $ {ENR} .Ext \ n "# download over proxy the file (option -c says repeat and reconect the download) wget --proxy = on -c ftp://tst.de/path/File $ {ZNR} $ {ENR} .Ext -O file $ {ZNR} $ {ENR} .Ext if ["$?" -ne 0]; then # Delete the File if an error before and file exists test -e file $ {ZNR} $ {ENR} .Ext && rm file $ {ZNR} $ {ENR} .Ext fi; done; # Go back in the last path cd -

Note / update

It is easier to add leading characters with the following function from the UbuntuUsers forum. The string operators used there (the numbers after the colon) are explained, for example, in the Linux User Article Part 3: String Processing and Regular Expressions. Below is a small script that uses the pad function and makes it available as, for example.

#! / bin / bash # Script to fill in # https://forum.ubuntuusers.de/topic/bash-variablengenerierung-mit-fuehrenden-nulle/ pad () {local s = $ 1 c = $ {2: -0 } p = $ {3: -} while [$ {# s} -lt $ c]; do s = "$ {p: 0: $ c - $ {# s}} $ s"; done echo "$ s"} #pad 1 3 # -> "1" #pad 123 5 0 # -> "00123" #pad xyz 5 abc # -> "abxyz" if [$ # -eq 3]; then pad $ 1 $ 2 $ 3 else if [$ # -eq 2]; then pad $ 1 $ 2 else echo -e "\ n *** Error 255: wrong number of parameters - use $ 0 [fill character] \ n" 1> & 2 exit 255 fi fi

BASH script: converts text files to utf8 CharSet

The following script converts a text file from another character set (CharSet) to Unicode (utf8). It tries to find out the previous character set on its own. To avoid data loss, the file is first renamed to a backup copy (with the "~" = tilde as the last character, as many UNIX editors do). When the script has completed the conversion, it writes the edited (converted) result back to the original file name. However, you then have to check yourself whether you are satisfied with the result of the processing. Otherwise you can delete the result and rename the file with the previous name.

#! / bin / bash # Script wich converts a file in 'text / plain' from an not utf8 char set to utf8 char set # # (c) LUG-VS (GPL) VERSION = "$ 0 Version 0.1.0 from 20.09. 2006 "# if [" $ 1 "==" "]; then echo "Please enter Filename as first option which should be converted" echo echo -e "INFO: \ n \ t To convert all old latin1 file-names in new utf8 file-names use:" echo -e "\ t \ t ' convmv --notest -r -f latin1 -t utf-8 * '\ n "exit -1 fi myNEWNAME = $ 1 myNEWNAMEsik = $ (echo $ {myNEWNAME} ~) myFILETYPE = $ (file -bi $ {myNEWNAME} | cut -d ';' -f1) myCHARSET = $ (file -bi $ {myNEWNAME} | cut -d '=' -f2) # if Filetype is convertable if ["$ {myFILETYPE}" == "text / plain"] && ["$ {myCHARSET}"! = "utf8"]; then # If sik file exists break with error message test -e $ {myNEWNAMEsik} && echo "File <$ {myNEWNAMEsik}> exists" && exit -2 mv $ {myNEWNAME} $ {myNEWNAMEsik} # Convert the old CharSet in utf8 echo "Convert $ {myNEWNAME} from $ {myCHARSET} to utf8" iconv -f $ {myCHARSET} -t utf8 -o $ {myNEWNAME} $ {myNEWNAMEsik} else # Print error Message echo "Filetype not 'text / plain' ($ {myFILETYPE}) or char set is 'utf8' ($ {myCHARSET}) "fi

BASH script: converts files from e.g. WMF to e.g. SVG

From time to time you want to convert files that are in any graphic format into another. This succeeds with the program convert quite easy from the ImageMagick® package. A list of the supported formats can be found on this page: http://www.imagemagick.org/script/formats.php. This script defines the source format in the variable at the beginning FORMATin and the output format in the variable FORMATout. By adjusting the appropriate file ends from the ImageMagick® format list, you should be able to build any converter. In the lines between echo -e and >> `echo $ {TEMPfile}` generate the actual processing script, any additions can of course be made. But be careful, you can of course do a lot wrong here. Therefore you should first write new commands with a echo first have a look before you can then remove them by removing echo actually used. A temporary directory with copied sample files can also be very helpful.

The script is used after the following lines have been copied into a file. You can open it, for example, with the Kate program in the target path on the command line, or in the terminal with Kate wmf2sfg.sh. Then the script is saved in the empty file using copy & paste (copy and paste = Ctrl + C and then Ctrl + V). The generated file wmf2sfg.sh is now made executable - z. B. in the terminal with chmod + x wmf2svg.sh. With most distros this can also be done graphically in the respective file manager by right-clicking on the file in the menu properties and then a tick in the field Executable (under the tab Permissions) puts. Called without parameters, the script also converts all files FORMATin (or the file type specified there, or the file extension) from the current directory and all subdirectories into the output format FORMATout (or the file type specified there, or the file extension). As a parameter you can also specify the path from which the script converts all files and those from the subdirectories.

#! / bin / bash # Simple script to "convert" a graphic file format to an other # # (c) LUG-VS (GPL) VERSION = "wmf2svg.sh Version 0.0.2 from 2006-12-27" # # Input: path # Output: changed files # # Changes: # 0.0.2: rebuild with temporary convertion file # 0.0.1: generation # FORMATin = .wmf FORMATout = .svg TEMPfile = `dirname $ 0` / $$. Sh EXECpath = . # trap is executed if script breaks (remove temporary file if exists) trap "echo '*** TRAP ***'; test -e $ {TEMPfile} && rm $ {TEMPfile}; exit" ERR # check if command exists else break which convert> / dev / null || echo "convert not found!" || exit; # check if filename exists if [-e $ {TEMPfile}]; then echo '$ {TEMPfile} exists => call this comand a 2-nd time' exit fi # if path exists and is a path => use it if [-d $ 1]; then EXECpath = $ 1 fi # generate temporary script for manipulation and made it executable # change in this section what is to do # the "echo" comand writes the comand lines in the $ {TEMPfile} echo '#! / bin / bash'> `echo $ {TEMPfile}` echo -e 'myFILEin = $ 1 \ nmyFILEout = `dirname $ 1` /` basename $ 1' $ {FORMATin} '`" "' $ {FORMATout} '"' >> `echo $ {TEMPfile}` echo -e 'echo convert $ {myFILEin} $ {myFILEout}' >> `echo $ {TEMPfile}` echo -e 'convert $ {myFILEin} $ {myFILEout}' >> `echo $ {TEMPfile}` echo -e '# write what you want to do without coment char "#" in this line' >> `echo $ {TEMPfile}` echo -e '# rm $ {myFILEin}; # remove "#" befor rm if you want to delete the source '>> `echo $ {TEMPfile}` chmod + x $ {TEMPfile} # echo what is to do echo' Start recursive convertion from * '$ {FORMATin}' in * '$ {FORMATout} # find all files ( not case sensitive) that matching filter and execut script find $ {EXECpath} -type f -iname "* $ {FORMATin}" -print0 | xargs -0 -n1 $ {TEMPfile} # debug => remove this line if not need cat $ {TEMPfile} # remove the temporary script rm $ {TEMPfile}

BASH script: securely erase hard drive

Alternatively: dc3dd

Perhaps you have already thought about giving away a hard drive, e.g. B. to sell on Ebay. You should therefore erase this hard drive so that your personal data is not inadvertently passed on in this way. That's the point of this script: it overwrites the hard drive in two steps. First, random numbers are written on the entire disk and then completely filled with zeros. This means that the data cannot be restored without considerable technical effort. So safe for laypeople and ambitious hobbyists. But be careful! With currently quite large disks of several hundred GB or more, deleting can take a day! Note: The hard disk should either be built into the PC or connected to the PC using a USB or eSATA port for this to work. It is not a good idea to do this with the / dev / sda1 or / dev / hda1 of a running GNU / LINUX system!

But it is also possible if you save this script on a USB stick and z. B. starts a Live-LINUX from CD / DVD and calls the script from there from the USB stick. B. want to sell a laptop without having to remove and reinstall the hard drive beforehand.

TIP: The call of the script only works if the path to the hard disk (device) is given to the script as a variable:

[Script name] / dev / sdX

The name of the script can be freely selected. I call it e.g. B. ShredderHDD.sh. The path to the hard disk depends on the hard disk itself. So / dev / sda for the first, / dev / sdb for the second, / dev / sdc for the third hard disk in the device, etc. But DANGER! If you are not absolutely sure that you are doing the right thing, you'd better ask someone who knows.Otherwise, please keep your hands off it! Irretrievably deleted data is deleted forever! Normally, no hard drive that is still required must be connected to the PC - only the CD / DVD drive or USB stick (ideally write-protected). Otherwise you accidentally delete the disk you still need!Download ShredderHDD.sh

#! / bin / sh # Deletes a complete device # Version 0.1.1 # From 2012-10-15 # (c) LUG-VS (GPL) # test whether it is available if ["` whoami` "! =" root "] ; then echo 'Insufficient rights - please log in as "root"!' exit 10 fi # Checks whether there are parameters if [$ # -lt 1]; then echo 'specify device e.g. "' $ 0 '/ dev / sdf"' exit 20 fi # test whether it is available if [! -b $ 1]; then echo 'Device does not exist' echo 'Specify device e.g. "' $ 0 '/ dev / sdf"' exit 30 fi # Assign device OF = $ 1 # Last query echo -n '*** Attention! Are you sure you want to delete the device (hard disk) '$ {OF}'? (y / n) 'read key echo "\ n" if ["$ {key}"! = "y"]; then echo 'Answer not "y" => canceled by user'; exit 1; fi; # Unmount drive echo 'Unmount drive' umount -f $ {OF} * # Write random numbers and then delete them date + "% F% T" echo 'Write random numbers to' $ {OF} dd if = / dev / urandom of = $ {OF} echo -en "\ n" date + "% F% T" echo 'Write zeros on' $ {OF} dd if = / dev / zero of = $ {OF} bs = 65536 date + "% F% T "echo 'Device (hard drive)' $ {OF} 'securely deleted' OF = # 4 times beeping #for ((INDEX = 4; $ {INDEX}; INDEX = $ (($ {INDEX} - 1))) ); do # beep # => beep is not found is also not an alias ??? !!! # wait #done # INDEX =

BASH script: Ensures that names from a file are created as a directory

This script was created by our member Gerhard for his order processing and made available to us as a GPL. Thanks to him for that!

This script reads data line by line in the format InputFile.txtin which orders in the formatting YYANR name are filed. This corresponds to YY the year ANR the three-digit order number and Surname the name of the job. This data is sorted by year and - if not yet available - created as a new subfolder. Similar entries that have already been created manually should also be recognized and thus not be created again.

#! / bin / bash # Loop for each line of a while read line; do # Individual components from the file YEAR = `echo $ line | awk '{print substr ($ 1,1,2)}' `RNR =` echo $ line | awk '{print substr ($ 1,3,3)}' `TXT =` echo $ line | awk '{print $ 2}' `# Check for existence in target directory SUCHSTRING = / home / otto / Auftraege-20 $ {YEAR} / $ {YEAR} - $ {RNR} * SUCHDIR =` (ls $ {SUCHSTRING} | awk '{print $ 1}') `files = $ (find $ {SUCHSTRING} 2> / dev / null | wc -l) # If not already there, create a directory if [! "$ {files}"! = "0"]; then mkdir "/ home / otto / Auftraege-20 $ {YEAR} / $ {YEAR} - $ {RNR} - $ {TXT}" fi done BASH script: Perform DynDNS update

This script was created by our member Gerhard for his order processing and made available to us as a GPL. Thanks to him for that!

This script checks whether the IP address of the router from the Internet cached in the file matches the current one (via service). If not, the new address is written to the file and then the address on the DynDNS server is updated with a link.

Since this check should be done at regular intervals, you can use the Linux cron service. This checks every minute whether a line within the config file (it used to be, but should no longer be used), is checked in the first five times separated by a space or tab until one matches the current time. If this is the case, the command is executed after the time specification. The file can be edited as a "root" user with or as a normal user. There you then write the following lines into it (whereby you can also omit the lines beginning with the line, as these are only comments for the operator.

sh & >> / dev / null


The following is the script that should ideally be saved under the name of the "root" user (i.e. you first have to log in with root (e.g. with).

#! / bin / bash ## find out my ip myip = "$ (dig TXT + short oo.myaddr.l.google.com @ ns1.google.com | awk -F '"' '{print $ 2}') " ; # Alternatively (remove comment # for next line) #myip = "$ (dig + short myip.opendns.com @ resolver1.opendns.com)"; ## which IP was before while read LINE do alt_ip = $ LINE done < /tmp/myip.txt ## echo Current: $ myip Old: $ alt_ip ## are the IPs the same? if [$ myip = $ alt_ip] then echo is the same >> /tmp/myiplog.txt else echo $ myip> / tmp / myip.txt; echo is different >> /tmp/myiplog.txt curl "http [s]: // " fi

BASH script: Carries out a comfortable and incremental backup / restore

With Zenity, this script uses a graphical interface with which the user can easily and conveniently do backup / restore. The events are recorded in a log file, as access rights are required for the folder.

#! / bin / bash -x # # (c) LUG-VS (GPL) # # Description: Carries out a comfortable and incremental backup. # Additional packages: Zenity library # Script name: backup & restore-de.bash # Version: from January 15, 2017 (German) # Note: The filename or folder name # must not have a space between them # Can only be executed with runlevel 5 or xorg and # root access rights required # Author: Giorgio Giuseppe Codardo ([email protected] # ============================== ============================================== # Declaration, definition and Initialization of variables. SOURCE = '' DESTINATION = '' typeset -i OPERATION = 0 RESULT = '' typeset -i BYTES = 0 DATE = $ (date +% d.% M.% Y) TIME = $ (date +% H:% M) # ====================================================================== =============================== # echo $ PATH # function verify_exit_status {if [$? -ne 0]; then zenity - -error \ --text = "An error occurred, so this script interrupted: \ n - Please restart with different parameters, \ n - or use debugging to search for the error. "exit fi} # # # =================== =================================================== ===== function start_backup {SOURCE = $ (zenity --file-selection \ --multiple \ --directory \ --title = "Select source directory ...") # # '|' of Zenity will be replaced '' so that you can use # cp on the command line. # SOURCE = $ {SOURCE // | / ''} # zenity --warning \ --text = "IMPORTANT! \ N - Mount external hard drive, \ n - For home directory: delete history and \ n - empty trash, \ n - Make sure the file system is compatible. " # DESTINATION = $ (zenity --file-selection \ --directory \ --title = "Select target directory ...") # verify_exit_status # # Start an incremental backup # cp --archive --update $ SOURCE $ DESTINATION | zenity --progress \ --title = "Backup in progress" \ --width = 400 --height = 200 \ --text = "Please wait ..." \ --pulsate \ --auto-close # # Here the bytes that were copied are determined and # the path is removed. # RESULT = $ (du -bs $ SOURCE) RESULT = $ {RESULT / '/' / '_'} BYTES = $ {RESULT% _ *} # zenity --info \ --text = "BACKUP executed successfully! \ n $ BYTES bytes were copied / updated. \ n More information: /tmp/backup-restore-de.log "} # End function start_backup # # ================== =================================================== ======= # function start_restore {zenity --warning \ --text = "IMPORTANT! \ n - Mount the external hard drive, \ n - Make sure that the file system is compatible." # SOURCE = $ (zenity --file-selection \ --multiple \ --directory \ --title = "Select source directory ...") verify_exit_status # SOURCE = $ {SOURCE // | / ''} # # DESTINATION = $ (zenity --file-selection \ --directory \ --title = "Select target directory ...") # verify_exit_status # cp --recursive --force $ SOURCE $ DESTINATION | zenity --progress \ --title = "Recovery in progress" \ --width = 400 --height = 200 \ --text = "Please wait ..." \ --pulsate \ --auto-close # RESULT = $ (du -bs $ SOURCE) RESULT = $ {RESULT / '/' / '_'} BYTES = $ {RESULT% _ *} # zenity --info \ --text = "RECOVERY successful! \ n The $ BYTES bytes restored. \ N More info: /tmp/backup-restore-de.log "} # End function start_restore # ======================= =================================================== = # Main program # # Input for superuser # PASSWORD = $ (zenity --password) # echo $ PASSWORD | sudo -S su # "Access Denied !!!" # OPERATION = $ (zenity --list \ --title = "choose action ..." \ --width = 800 --height = 400 \ --column = "number" --column = "action" --column = "Description" \ 1 Backup "Execution of an incremental backup." \ 2 Restore "Restoration from saved data.") Case $ OPERATION in 1) start_backup echo "Backup was carried out on: $ DATE at $ TIME and $ RESULT bytes saved / updated "\ >> /tmp/backup-restore-de.log 2> & 1 verify_exit_status ;; 2) start_restore echo "Restoration was carried out on: $ DATE at $ TIME and $ RESULT bytes backed up / updated" \ >> /tmp/backup-restore-de.log 2> & 1 verify_exit_status ;; *) verify_exit_status ;; esac # exit 0 # ============================================= ===============================

BASH script: Only filters the error messages from log files

With Zenity, this script uses a graphical interface with which the user can easily see search results from log files.

#! / bin / bash -x # ===================================================================== ==================================== # # (c) LUG-VS (GPL) # # Description : Only filters the error messages from log files # in / var / log. # Additional packages: Zenity Library # Script name: errorlog-DE.bash # Version from 04/29/2021 (Deuch) # Last change: 04/29/2021 # # Author: Giorgio Giuseppe Cotardo # ([email protected] ) # # ========================================================================== ============================== # Initialization and definition of variables echo $ PATH RESPONSE = 0 RETURN_VAL = 0 YES = 0 NO = 1 # # ================================================ =============================== # SEARCH FUNCTION # =============== =================================================== ============ function search_error_log {SELECTION = $ (zenity --list \ --title = "Choose option ..." \ --width = 800 --height = 400 \ --column = "No." --column = "File" --column = "Description" \ 1 boot "Log of boot" \ 2 kernel "Log of the loaded kernel" \ 3 system "System log" \ 4 apport "Log of unexpected error message" \ 5 auth "System login resp.Login ") case $ SELECTION in 1) grep fail /var/log/boot.log> /tmp/resultlog.txt RETURN_VAL = $? FILE = / tmp / resultlog.txt if [$ RETURN_VAL -eq $ YES]; then zenity --text-info \ --width = 800 --height = 400 \ --title = "Search result in the file boot.log" \ --filename = $ FILE else zenity --info \ --width = 400 - height = 100 \ --text = "No search hit." fi ;; 2) grep fail /var/log/kern.log> /tmp/resultlog.txt RETURN_VAL = $? FILE = / tmp / resultlog.txt if [$ RETURN_VAL -eq $ YES]; then zenity --text-info \ --width = 800 --height = 400 \ --title = "Search result in the file kern.log." \ --Filename = $ FILE else zenity - -info \ --width = 400 --height = 100 \ --text = "No search hit." fi ;; 3) grep fail / var / log / syslog> /tmp/resultlog.txt RETURN_VAL = $? FILE = / tmp / resultlog.txt if [$ RETURN_VAL -eq $ YES]; then zenity --text-info \ --width = 800 --height = 400 \ --title = "Search result in the syslog file." \ --filename = $ FILE else zenity --info \ --width = 400 --height = 100 \ --text = "No search hit." fi ;; 4) grep fail /var/log/apport.log> /tmp/resultlog.txt RETURN_VAL = $? FILE = / tmp / resultlog.txt if [$ RETURN_VAL -eq $ YES]; then zenity --text-info \ --width = 800 --height = 400 \ --title = "Search result in the file apport.log." \ --filename = $ FILE else zenity --info \ --width = 400 --height = 100 \ --text = "No search hit." fi ;; 5) grep fail /var/log/auth.log> /tmp/resultlog.txt RETURN_VAL = $? FILE = / tmp / resultlog.txt if [$ RETURN_VAL -eq $ YES]; then zenity --text-info \ --width = 800 --height = 400 \ --title = "Search result in the file auth.log." \ --filename = $ FILE else zenity --info \ --width = 400 --height = 100 \ --text = "No search hit." fi ;; *) esac # zenity --question \ --width = 400 --height = 100 \ --text = "Continue searching?" RESPONSE = $? } # ========================================================================== ============================= # MAIN # ================== ============================================================================= ========= while [$ RESPONSE -eq $ YES]; do search_error_log done echo $ RESPONSE

BASH script: splits a compressed file into equal parts or reassembles an already split file

This script uses the Zenity graphical interface.

#! / bin / bash -x # ===================================================================== ==================================== # # (c) LUG-VS (GPL) # # Description : Splits / splits a file into a desired # size and after selection, concatenates it in an # original size. # The file must first be compressed in the permitted format #: .zip, .tar, .gz, .rar, .xz # The file names are named with a random number. # Additional packages: Zenity library # Script name: split & cat-de.bash # Version: from Mon 29 Dec 2014 12:06:22 CEST (German) # Last change: on Sa 28 Sep 2019 12:24:11 CEST # Note: The filename or folder name # must not have a space or special character # between them. # Can only be executed with runlevel 5 or xorg. # Author: Giorgio Giuseppe Codardo # ([email protected]) # # ================================= ============================================= # Initialization and definition of Variable echo $ PATH export STATE = 0 NEWDIR = $ RANDOM STATUS = $? ZENITYPATH = "/ usr / bin / zenity" INFOFILE = "/ home / INFO.txt" # # ============================ ================================================= # FUNCTION SPLIT # ============================================== =============================== # Select file ... function Split () {FILENAME = $ {FILENAME // '' / '/'} # # ------------------------------------------- ---------------------------------- # Check extension of the file gz, tar o tar.gz etc. # # -------------------------------------------------- --------------------------- ESTENSIONE = $ {FILENAME: (- 3)} case "$ ESTENSIONE" in "zip") STATE = 1 ;; "tar") STATE = 1 ;; ".gz") STATE = 1 ;; "rar") STATE = 1 ;; ".xz") STATE = 1 ;; *) # As default STATE = 0 # for other file formats. ;; esac if [$ STATE == 0]; then zenity --error \ --text = "An uncompressed file was selected!" exit -1 fi # --------------------------- -------------------------------------------------- # NEWDIR = `date` # NEWDIR = $ {NEWDIR // ',' / '_'} # NEWDIR = $ {NEWDIR // '' / '_'} FILESIZE = $ (zenity --scale \ --text = "Set the maximum size of the split file (in MByte)" \ --value = 100) FACTOR = 1000000 # FILESIZE = $ ((FILESIZE * FACTOR)) # ---------------- -------------------------------------------------- ----------- # Create a medal with the same file name ... # ---------------------------- ------------------------------------------------- DESTINATION = $ (zenity --file-selection \ --directory \ --title = "Select target folder ...") if zenity --question \ --text = "Generate a random file name?"; then mkdir / $ DESTINATION / "$ NEWDIR" cd / $ DESTINATION / $ NEWDIR else NEWDIR = $ (zenity --entry \ --title = "Enter folder name." \ --text = "A new folder will be created" \ - -entry-text = "New Directory") mkdir / $ DESTINATION / "$ NEWDIR" cd / $ DESTINATION / $ NEWDIR fi # # Here we go ... # split --numeric-suffix --byte = $ FILESIZE $ FILENAME $ NEWDIR "_" # # zenity --notification \ --window-icon = "Info" \ --text = "I files frazionati si trovano nella directory di destinazione." } # ========================================================================== ============================== # FUNCTION CAT # ================= ============================================================================= ========== function Cat () {FILELIST = $ (zenity --file-selection \ --multiple \ --title = "Mark all files for linking ...") FILELIST = $ {FILELIST // '|' / ''} DESTINATION = $ (zenity --file-selection \ --directory \ --title = "Select target folder ...") OUTPUTFILE = $ (zenity --entry \ --title = "Enter data name with appropriate extension ..." \ --text = "New file name" \ --entry-text = "*. Gz, * .zx, * .zip, * .tar") cat $ FILELIST> $ DESTINATION / $ OUTPUTFILE zenity --notification \ --window-icon = "Info" \ --text = "Concatenate successfully executed and are located in \ $ OUTPUTFILE." } # ========================================================================== ============================= # MAIN # ================== =================================================== ========= while # Check if zenity is installed ... find $ ZENITYPATH if [$ STATUS = 1] then echo "Zenity not found!" fi zenity --question \ --text = "Continue with the script?" ; do zenity --text-info \ --title = "Information" \ --filename = $ INFOFILE \ --checkbox = "I agree!" # The return value corresponds to the string from split & cat RESULT = $ (zenity --list \ --title = "Select the desired operation:" \ --column = "Operation" --column = "Description" \ SPLIT "Splits in the same size" \ CAT "Concatenate the split file") if [$ RESULT = "SPLIT"] then FILENAME = $ (zenity --file-selection \ --title = "Select file") Split # Function Call else $ RESULT = "CAT" Cat # Function Call fi done exit 0 # ===================================================================== =====================================

annotation

Instead of the 'GTK' based Zenity you can of course also use the Qt / KDE pedant KDialog. See also:

BASH script: Performs a complete backup of your 'Thunderbird'

updated on 05/22/2021

Here is a very simple script that saves your own .thunderbird folder in a backup folder (compressed). You can still optimize, expand and automate if you want. In my case, this simple variant is enough for me, because I consciously use it manually after individual actions such as the mass retrieval of numerous mail accounts. The calendar entries in the calendar module ('Lightning') are also saved if you use this. This script assumes the following: A directory called 'bin' and a directory called 'backup' exist in their own HOME directory:

cd mkdir bin backup

The script must be saved in 'bin'. The name is freely selectable, I got it 'tbbup' (Thundredsbearth B.ackup) called. It still has to be made executable after creation:

cd am chmod u + x tbbup

As soon as you log on to a console (terminal), you should use a standard distribution such as B. Execute Debian simply by typing

user @ localhost ~ $ tbbup

start. (Please only enter the bold print here. The preceding part is the prompt!) If Thunderbird is running, the program (Thunderbird) will be terminated.

background: If Thunderbird is started, you should not make a backup in order to be able to restore it at all. When the TB is running, there is a lock file that contains a time stamp. The file will be deleted when you exit. If you later restore a TB that was backed up during operation, this lock file causes problems and TB cannot be started afterwards.

If Thunderbird is not running, the backup will be carried out immediately.

#! / bin / bash # name of script: tbbup - Thunderbird Backup-Script # license: GPLv2 or higher # author: [email protected] # date of first creation: 12/05/2015 (Dec. 5, 2015 ) # should do the following: # check if thunderbird is running and stop it if so # than create a tar.gz-file named 'tb_ [date] _ [time] .tar.gz in a directory # named' backup 'in your home-directory # killall -i thunderbird tar cvfz ~ / backup / tb _ $ (/ bin / date +% F_% H:% M) .tar.gz ~ / .thunderbird / * exit 0

Note: Please note that restoring via the tar command to the hidden .thunderbird folder in your HOME directory works:

tar -xzvf backup / tb_ [YYYY-MM-DD_hh: mm] .tar.gz .thunderbird

With absolute paths:

tar -xzvf /home/[username guard/backup/tb_[YYYY-MM-DD_hh:mm].tar.gz /home/[username guard/.thunderbird

where the part [YYYY-MM-DD_hh: mm] must be replaced with the actual values ​​for date and time! So please don't forget that there is a dot in front of the 'thunderbird':

.thunderbird

The absolute path in this case would be: '/ home / [your username] /. Thunderbird'.

BASH script: SYSInfo to practice

This script is for training purposes only. inxi does a lot more and better work here. Graphical tools such as system monitoring are certainly better and clearer. But to understand how scripts work and work, and to just get started with scripting, this is good practice.

#! / bin / bash # name of script: sysinfo # license: GPLv2 or higher # author: [email protected] # date of first creation: 04/29/2017 (Apr. 29, 2017) # should do the following: # output a salutation, introduce the hostname, display date # and time as well as the kernel version used and a final # salutation at the end. # Please consider to play with it and insert your own # commands you are interrested in like e. G. # cat / etc / debian_version; df -h ~; ls echo "Welcome $ (whoami)" echo "My name is '$ (hostname)'" echo "The date and time is $ (date)" echo "My kernel version is $ (uname -r)" echo "Thank you for using sysinfo-script. " echo "Good bye!"

Since this script is under the GPL v2, you can use, change and redistribute / publish it as long as you put it under the same license. So you can let off steam with it. But don't forget: As soon as you manipulate the system or use commands with a system-changing character, such as the rm command, it can also be harmful, depending on the constellation. So you use all scripts here at your own risk!

If anything is unclear or there are obvious mistakes, you are asked. Write to the mailing list ([email protected]) or ask one of the authors directly at one of our regulars. We learn from our mistakes and from each other every day.

BASH script: automatically delete files / directories from a list

Every now and then you would like to delete several files and directories that are in a simple list. For example, you can use the command find As e.g. described here chapter 1.2, simply redirect to a file (see -exec simply through >> Files to be deleted.txt replace). The file can then be conveniently edited with the text editor such as Kate (simply delete or add lines with the complete directory name). The program is copied back into a file that can be made executable with and then executed with the path name.

Danger: The program really deletes all data without further inquiry (even complete directory paths). Therefore, make absolutely sure that it does not contain any directories of the Linux operating system like / am, /Etc and many more!

#! / bin / bash # Deletes files / directories of the file "ZuLöschendeDateien.txt" without any confirmation. # # (c) LUG-VS (GPL) while read line; do echo "*** Delete file / directory <$ line> final and final without confirmation! ***" rm -rfv "$ line" done Left BASH programming

A few more links where you can find more information about BASH programming.

Other useful scripts from the Internet

See also scripts in the article Backup.

Script to search for translations

Elimar has created a script called trans-ask that can be used to translate a word into another language. What is special is that the results of various translation programs are displayed next to each other in windows. The following language pairs are currently supported:

  • Spanish <-> German
  • English <-> German
  • Spanish <-> English

See GitLab

Renaming files with special characters to ASCII compliant names

chnames.sh (or also under) by Conny Faber is a BASH script for renaming file names in an ASCII based version without special characters.


Back to the Linux help page or the main page