0% found this document useful (0 votes)
86 views

Coding Tricks and Tips - May 2023

Uploaded by

Ian Wallace
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
86 views

Coding Tricks and Tips - May 2023

Uploaded by

Ian Wallace
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 76
Coding and . Programming Advanced guides and tutorials for coding Linux and Windows Batch Files We share our awesome coding tips and projects to push | > your skills further Next level fixes and secrets help you get more from Linux distributions (% TRICKS & TIPS ato pel (6l-19 Available on KO iPhone ie 3 ios 16 BSE Cg ay Ns eC] aie Sy FT i a Costa TRICKS LAS Coding and . Programming Coding and Programming Tricks & Tips is the perfect digital publication for the user that wants to take their skill set to the next level. Do you want to enhance your user experience? Or wish to gain insider knowledge? Do you want to learn directly from experts in their field? Learn the numerous short cuts that the professionals use? Over the pages of this new advanced user guide you will learn everything you will need to know to become a more confident, better skilled and experienced owner. A user that will make the absolute most of their software and ultimately their coding skills themselves. An achievement you can earn by simply enabling us to exclusively help and teach you the abilities we have gained over our decades of experience. to rer the page Journey continues and we will be wi ‘ith at every stage to ade ‘form and ultimately ‘spite you to 90 Further. 10 2 14 16 18 20 What is a Batch File? Getting Started with Batch Files Getting an Output Playing with Variables Batch File Programming Loops and Repetition Creating a Batch File Game 24 Why Linux? 26 The Best Linux Distributions 28 Equipment You will Need 30 Creating a Linux Installer on Windows 32 _ Installing Linux on a PC 34 _ Installing a Virtual Environment 36 _ Installing Linux in a Virtual Environment 38 Getting Ready to Code in Linux 40 Creating Bash Scripts ~ Part 1 42 _ Creating Bash Scripts ~ Part 2 44 Creating Bash Scripts ~ Part 3 46 Creating Bash Scripts —Part 4 48 Creating Bash Scripts —Part S 50 Command Line Quick Reference yO Reels ako ee ees) 54 _ Planning your Code 56 _ Finding Resources 58 Creating a Loading Screen 60 Planning a Text Adventure 62 _ Text Adventure Script 64 RetroCoding 66 Text Animations 68 Common Coding Mistakes 70 _ Python Beginner's Mistakes 72__ C++ Beginner's Mistakes Py mn hil ie A ia ees dt = : ee oe stad Set Coding with Wind Coding with — Windows 10 — Batch Files DR aC ra eee eae Te in scripting language? Batch files have been ER Rete eT mT EI RT CR RE oh ee RI ea uric eeacucie they are still there and still just as capable as Ae RCE Cee Cn Cn eee erat administrators still use, so it’s worth spending a bit of time learning how they work, and Rs Meme introduces batch files, and covers user interactions, variables, loops and even a batch Get eee Curated tae @ Coding with Windows 10 Batch Files What is a Batch File? .~BAT MAN ‘AWindows batch file is simply a script file that runs a series of commands, one line at a time, much in the same fashion as a Linux script. The series of commands are executed by the command line interpreter and stored in a plain text file with the .BAT extension; this signifies to Windows that it’s an executable file, in this case, a script. Batch files have been around since the earliest versions of Microsoft OS. Although not exclusively Microsoft atch files are mainly assaclated with Microsofts operating systems. In the early days, when a PC booted into a version of DOS (which produced _asimple command prompt when powered up), the batch file was used in the form of a system file called Autoexec.bat. Autoexec bat was script that automaticaly executed (hence Autoexec) -ommands once the operating system had finished dealing with the Configsys file When a user powered uptheir DOSbas mputer, and once the BIOS had Finished checking the system memory and so on, DOS would lookto the Config.sys File to load ary specific display requirements ‘and hardware drivers allocate ther a slotin the ‘available memory, assign any memory managers and tell the system where ommand,com file, isthe commandline interpreter for DOS, was Once it had done that, then the autoexec.bat file took over and ran through each line inturn, loading programs that would activate the mouse or ‘optical drive into the memory areas assigned by the Config. sys fle. The DOS user of the day could opt to create different Autoexec. bat files depending on what they wanted to do, For example, iF they wanted to play a game and have as much memory available as possible, they/d create a Configsys and Autoexec.bat set of files that loaded the bare minimum of drivers and soon. they needed access to the network, an Autoexecbat file could be createdto 3, SAA aan 121 ‘The Autoexecbatfile was aPC user's First experience with a batch file wom ppublestionscom Batch files are plain text and often created using Notepad. Batch files were often used as utility programs, to help users with complex tasks. load the network card driver and automaticaly gain access tothe network. Each ofthese unique setups would be loaded on to a Floppy disk and booted as and when required by the user, fhe Autoexec.bat was the First such file many users came across in sting lives since many had come from a 16-bit or even &-bit background; remember, this wasthe late eighties and early nineties. The batch File was the user's primary tool For automating tasks, creating shortcuts and adventure games and translating complex pracesses into something far simpler their PCbased con Nowadays however, a batch file isnt just for loading in drivers and such when the PC boots. You can use a batch file in the same way as any other scripting language file, in that you can programit to ‘ask foruser input and display the results on the screen; or save to afileand even sendit toa locally or network attached printer. You ipts to back up your files to va ompare date stamps and only back up the most recently changed content as, ‘well as program the script to do all this automatically, Batch files are remarkably powerful and despite them not being as commonly used asthey were during the older days of DOS, they are still there and n be utilised even inthe latest version of Windows 10; and can be as complex or simple as you want them to So what do you need to star batch file programmingin Windows? Well, as long as you have Windows 10, or any older version. Windows for that matter, ou can start batch file programming immediately. ll you need is to be able to open Notepad and get to the command prompt of Windows. We show you haw it all works, so read on, What is a Batch File? BATCH FILE POWER Just ke any other programming interface that can directly interrogate and manipulate the system, batch files require acettain amount of care when programming l’s hard to damage your system with a batch file, asthe mare important lements of the modern Windows system are protected by the User Account Control (UAC security; UAC works by only allowing elevated privileges access to important system ies Therefore if you create a batch file that somehow deletes a system file, the UAC activates and stop the process. However, you're working in the command prompt with elevated privileges to begin with, asthe Administrator, then the UAC won't question the batch File and continue regardless ‘of what files are being deleted ‘That said, you're not likely to create a batch file that intentionally wipes out your operating system. There are system controlsin place to that; butt’s worth mentioning as there are batch files available on the internet that contain malicious code designed to create problems. Much ikea virus, a rogue batch file (when executed with ‘Administrator privileges) can cause much mayhem and system damage. In shor, don't randomly execute any batch file downloaded from the Internet as an Administrator, without First reviewing what it does. ‘You can learn more about batch filesin the coming pages, so don’t worry too much about destroying your system with one, Allthis just demonstrates how powerful the humble batch file canbe, You can create complex batch files or simple ones that display AASCIlimages on screen, wv pcpubliestionseam Coding with Windows 10 Batch Files Getting Started with Batch Files A NEW BATCH ‘Throughout this section on batch files we're going to be working with Notepad, the command prompt and within a Folder called ‘Batch Files’. To begin with, let's see how you get to the Windows command prompt. prompt window, enter: c/w. This istsall the files and directories from The windows — | stEP 3 ) While at the comma prompt may look alittle =a where you are at the moment in the system. In this case, that's your Jaunting to the newcomes a Home directory that Windows assigns every user that logs in. You butit’s simply another = can navigate by using the CD command (Change Directory). Try interface (or Sel) used to coe oe access the filesystem. You " t = can goanywhere you tke in the command prompt, as you would with the graphical S interface. To begin, click on the Windows Start button and enter CMD into the search box. Then press Return BED Sec tesecreatitntecmmnsronst EES te monet sntsconge anit {Desttop Ape ands new window pope. The Documents this means you're in the Documents Command Prompt window isnt much to look at to begin with but directory. Now, create a new directory cll Batch Files. Enter: you can see the Microsoft Windowsversion number and copyrights watch putesm information followed by the prompt itself. The prompt detailsthe : surrent directory or Folder you'rein, together with your username. You need the quotations because without them, Windows creates two directories: Batch an newly created Batch Files, les. Now change directory into the You won't need the quotes to chang: directories wom ppublestionscom Now thatyouhavethe econ set where you SIPS store your batch files, here is how you can create Wows Str tton guste ete Notepad nd clcon the serch resto open he Notepad progr Notepodisa Sle textedtr bts or creating atch ss wth To create your Firs batch fie, enter the Following into Notepad Becho of: ‘echo Hello World! By default, a batch file displays all the commands that itruns through, line byline. what the @echo off command does is turn that feature off forthe whole script; with the ‘@ at) sign to apply that command o itself. rc ot EEE When saving anything in Notepad the default extension txt, to denote a text file, However, you ‘want the extension to be tat. Click on File > Save As and navigate tothe newly created Batch Files directory in Documents. Click the ‘drop-down menu Save as Type, and select All Files From the menu. In File Name, cal the file Test bat. ( Getting Started with Batch Files Back t the command prompt window, enter: ‘din/ again to list the newly created Test bat le By the way, the /w part of dirw means the files are listed across the screen as opposed to straight down. Enter di if you want {although you need more files to view) butit's considered easier to read with the /w flag, BERD To execute the batch file you've just created, simply enter its name, Test, in the command prompt window. You don't need to add the bat part, as Windows recognises itasan executable file, and the only one with that particular name in the current directory. Press return and see how you're greeted with Hello World in the command prompt. PET R the echo command displays whateveris after it tothe screen. Right-click the Test.bat file from Windows Explorer and select Edit to add more echo commands if you tke Try this: @echo off echo Hello World! echo This is my first batch file echo. echo With a Blank line between! Remember to save each new change to the batch ile EP Coding with Windows 10 Batch Files Getting an Output While it’s great having the command prompt window display what you're putting after the echo command in the batch File, it's not very useful at the moment, or interactive for that matter. Let's change up a gear and get some output. INPUT, OUTPUT Batch files are capable of taking a normal Windows command and executing it, while also adding extra options and Flags in to BARRED cc tree srck wiceeah uncance ‘View. Start with the @echo off command and under that add Le “c#\users\YOURNAME\Documents\Batch Files" > 2 \users\YOURNAME\dirview. txt ‘Substitute YOURNAME with your Windows username. FETED the newline uses the dircommandto list the contents of the directory Batch Files, in your Home: directory, dumping the output toa text ile called ai'rvitew txt in the root of your Home directory. This done, so that the Windows UAC doesn't require elevated permissions, as everything i in your ‘own Home area. Save and run the batch file. Yuhave no doubt noticed that there sno UEP indication that the batch file worked as there's nomesningul output on the seen However, younoW open Explorer and browse to ¢:\sers\ZOORNAME, remembering to subste YOUTAANE with your windows username, nd double dik the dirview. txt le youcansee the batch e's Uti line to the bateh fie: notepad-exe €# \users\YOURNAME\ai view. txt Save the fle and once again run from the command prompt. This, time, it creates the output and automatically opens Notepad with the output contents. OUTPUT WITH VARIABLES Variables offer a more interesting way of outputting something to the screen and create a higher level of interaction between the user and the batch file. Try this example below. FETED eestea newbatch file and callit namebat. start EAI thisis extremely useFuliFyou want to create @ with the Becks ££ command, then add the unique, personal batch file that automatically runs following ines: when a user logsinta Windows. Using the default systems variables that Windows itself creates, you can make a batch file that greets each user: set /p name= Wi echo Hello, sname’ is your name? Note: there's a space after the question mark. This isto makeit look S@eH® OFF neater on the screen, Save itand run the batch fl. echo Hello, SUSERNAMES ho echo Thanks for logging in. Currently the network ig operating at 100%% efficiency. ee echo echo Your Home directory is 10 fed at: SHOMEPATHS - echo The computer name you're logged in to ii ‘SCOMPUTERNAMES = The st /pname creates a variable called name, Sue with the /p part indicating that an ‘=prompt string’ istofollow. he Set command displays, sets oF removes system and environmental variables For example, when the command prompt window enter: PRED seve and execute the batch file changes; you can ‘overwrite and still use name bat f you want. The = batch ile takes the current system variables and reports them To view the current system variables, Note the name=variable we accordingly, depending on the user's login name and the name oF just created, the computer. Note: the double percent symbol means the percent sign willbe dsplayed, ands nota variable. FRPETD 2ternatively you can runthe batch fle and display itonthe user's desktop as a text fle: @echo off PR tics seed ith Setconbecatedwth the @2be"Heloy,SUSHRNAEL. > ce AHONBENTHE users txt echo. >> ctBHOMEPATHE\User. txt 6VARIABLENAME% syntax. Inthe batch file, we used the newiy created Siname% syntax to call upon the contents of the variable called name. Your username, For example, isstored as @ Thanks for logging in. Currently the network is operating at 100%% efficiency. >> c:$HOMEPATH¥\, variable. Try thisina batch file — ee le ace echo. >> c#tHOMEPATHE\user.txt echo Hello, SUSERNAMES. What are you doing? echo Your Home direct fated at SHOMEPATHS >> crSHOMEPATH®\u echo The computer name you're logged in to is MPUTERNAMES >> crSHOMEPATHS\user. txt echo. >> c:SHOMEPATHS\user. txt notepad ¢:SHOMEPATHS\user. txt ‘The > outputs toa new file called user.txt, while the >> adds the lines within the Fle Coding with Windows 10 Batch Files Playing with Variables USING MORE VARIABLES Here's a good example of mixing system and environmental variables with some of your own creation, along with a number of external Windows commands, FETESERD reste a new batch file called st batand startitofF sie (ieee : fF any directory and postitasa text fileto the user's en. Add the following tothe ist bat batch file: es on the compute hat displays the conte PR cand execute the batch le within he BEEED vies termononee settee tocenter any ofthe directories displ ries From theroat of the C:\ rive; andasany _ generated, inthe Form of ‘\directory’, Providing the user enters a user under Windows has permission to see this, there's no UAC valid directory its contents are displayed a the view variable here along with SHON and the text file 35 text fle, We created PATHS, to store the input wom ppublestionscom FETED t's atuays.a good idea, when creating text files forthe user to temporarily view, to clean up after yourself. There's nothing worse than having countless, random text files cluttering up the file system, That being the case, let's clear up with: cls del /Q view.txt del /Q List.txt echo All files deleted. System clean, FPPD the additions to the batch file simply lear the command prompt window (using the cls command) and delete both the view.txt and lis xt Files that were created by the batch file. The /Q flag in the del command meansit deletes the files without any user input or notification. The final message. informs the user that the files are removed. Bap one your systemis configured, Yyou may not get any ‘icectory information atallora message stating Access Denied, Thisisbecause the UAC isblocking accessto protected areas of the system, ke c\Windows ‘or C\Program Files ‘Therefore, you need to run the batch file asan ‘Administrator. Click the ‘Windows Start button and center CMD again. =o e mn ( Playing with Variables BETEEE DD stead of left clicking on the Command Prompt result, as you did the Fist time you opened it, right-click t and from the menu choose Run as Administrator. There is risk that you could damage system files asthe Administrator but as ong as you're careful and don't do anything beyond viewing directories, you wil be okay & Oo 6 Fiters Best match fH Commend Promot Run as administrator se Open file location Pin to Start trad Pin to taskbar FETSEDD This action riggers the UAC warning message, ‘asking you F you're sure you want to run the \Windows command prompt with the elevated Administrator privileges. Most ofthe time we wouldn't recommend this course of action: the UAC is there to protect your system. In this case, however, click Yes. ¢ User Account Control y Do you ets D show seas PEPPER) With the UAC active, che command prompt looks a litle diferent. For starters, i's now defaulting to the CAWINDOWS\system32 Folder and the top of the windows is labelled Administrator. To run the batch file, you need to navigate to the Batch Fle ciectory with: ed \Users\USERNAME\Documents\ Batch Files. To helo, press the Tab key to auto-complete the directory names, Coding with Windows 10 Batch Files | Batch File Programming It’s the little additions we can make to a batch File that help it stand out and ultimately become more useful. While the Windows graphical interface is still king, the command line can do just as much, and this is where batch files come into their own. SEARCHING FOR FILES Here's an interesting little batch file that you can easily extend for your own use. It asks the user fora file type to search for and displays the results. PTISEB We ae introducing a couple of new commands PPE DD) Nowlet’s extend the seek bat batch fie into the mixhere but we think they're really useful, Createanew batch le called seek bat ondin it pu echo off els oan color 2 = echo Please enter the type of fle you want to echo Please enter the type of le you want to Seafeh for (MP3, DOC, JPG for example) search for (MP3, 0c, JES for example) oe ‘echo. Where /R c:\ *.¥ext% > found. txt notepad.exe found.txt als color del /0 found. txt FEED the new command inthis instance is color FETED “other new command, where, looks fora specific (Americansed spelling). Color, as you already file or civectory based on the user's requirements. ‘assume, changes the colour of the command prompt display. The _In this case, we have created a blank variable called ext that the user ‘olor attributes are specified by two hex dist, the first corresponds can enter the filetype in, which then searches using Where and tothe background colour ofthe Command console and the second dumps the results in a text file called found.txt. Save and run the to the foreground, and can be any ofthe following values: batch file O=Black 8=Grey 1=Blue 9 = Light Blue 2=Green A= Light Green 3=Aqua B= Light Aqua 4=Red C=LightRed 5=Purple D-=Light Purple 6=Yellow E=Light Yellow 7=White F = Bright White CHOICE MENUS Batch File Programming eC” Creating a menu of choices isa classic batch file use and a good example to help expand your batch file programming skits. Here's some code to help you understand how it all works. ESTESED ether than using avariableto process a user's response, batch Files can instead use the Choice ‘command in conjunction with an ErorLevel parameter to makea menu. Create a new file called menu.bat and enter the following: Becho off cle choice /M “Do you want to continue? Y/N" Af errorlevel 2 goto Af errorlevel 1 goto ¥ ‘goto End: FETED ning the code produces an error as we've called Goto command without any reference toit inthe file, Goto does exactly that, oes to aspeaific line inthe batch File, Finish the File wth the Following and run it again: aN ‘echo. ‘echo You goto End chose No. Goodbye. Y ‘echo. ‘echo You chose Yes. Hello send FETTER) the output from your choice is different depending on whether you pick or N. The:End part simply signifies the end ofthe file (also known as EOF), without tthe batch fileruns through each ine and display the ¥ response even Ifyou enter N;soit’s important to remember to follow your Goto commands. BETIS Erortevels are essentialy variables and the /M switch of Choice allows adescritive message string to be displayed, Extend this menu with something new: @echo off cls echo. echo echo echo) echo. echo) echo. echo) echo echo) Please choose a directory. Press 1 for e:\music Press 2 for c:\Documents Press 3 for c:\Pictures echo. echo Press @ for c:\Videos echo. echo choice /c 1234 if errorlevel 4 goto if errorlevel 3 goto iff errorlevel 2 goto if errorlevel 1 goto Videos Pictures Documents Music PEPTED Now acd the Goto sections: Videos els cD $HOMEPATHE\Videos echo You are now in the goto End Videos directory. seletures cls CD *HOMEPATHA\PLetuEeS echo You are now in the goto End Pictures directory. Documents cls cb $HoMEPATH\Documents echo You are now in the goto End Documents directory, eMusic cls CD $HOMEPATHE\Muste fecho you goto End 2 now in the Music directory. nd BERTI) when executed, the batch fle dsplaysamenuand with ‘ach choice the code changes directoryto the one the User entered, The %HOMEPATH system variable wilenter the curently loggedin user's Music Pictures ando directories, and nt aryone else's Coding with Windows 10 Bat Loops and Repetition COUNTERS Creating code that counts in increasing or decreasing number sets is great for demonstrating loops. With that in mind, let’ look at the IFstatement alittle more, alongside more variables, and introduce the Else, Timeout and eof (End of File) commands. Start by creating a new batch filecalled count. bat Enter the following, save itand run: jet /a count sunters+1 The count Sure bat code starsat aurber one and ts, seraling down the serena teaches 10 between rumbersandthe faterent contin unter erable the eof End OF Fits singthe | wom ppublestionscom BED ‘The count-bat is a rough w loop; a better approa nple instead smonstrating 2 for loop, BED Breaking it down, there's For, then the /L switch, which handles a range of numbers Then the parameter labelled as ‘é8sn to denate a number. Then the in (1,1,99) part, which tells, the statement how to count, a5 in (start number) 1 steps to take), 99 the end number), The next partis do, meaning 00 whatever command is after You can include the pause between the numbers Susas easily enough within the Far simpler For loop by. ‘adding multiple commands after the Do For loop. The brackets and ‘ampersand (8) separate the different commands. Try this: Becho of for /1, 88m in (1,1,93) do. (echo Joobreak > mul) Sin & timeout /T 1 (Loops and Repetition Thee are ferent ways ung the Fortop. UP this example, the code creates 26 directories, one For each letter of the alphabet, within the directory e\test which the batch file makes using the MD command: FOR 88F IN (a,b, 6,4/0,£,9/b, iy 5+ ke Lele, O,Brde Er Sit eUr¥/ WX, V2) DO (md C:\test\ 488 FETED Ore of the great time saving uses of batch files isto create multiple, numbered files. Assume that you ‘want twenty Five text files within a directory, ll numbered from 1 to 25. Aor loop much like the previous example does the trick: echo for / ot Stn in (1,1,25) do copy nul $4n.txt BPTI DD you open windows Explorer, and navigate tothe Batch Files directory where you're working from, you can now see 25 text files all neatly numbered, OF course, you can append the file name with something like user txt and so.on by altering the code to read: fecho off for / ¥¥n in (1,1,25) do copy nol Usert¥n.tx Freee (0025 canbe powerful and extremely useFul ‘elements ina batch file. while creating 26 directories may not sound too helpful, imagine having to create 1,000 users on a network and assign each one their own set of Unique directories. Thisis where a batch file saves an immense amount of time. Should you ever get stuck when using the vrious SUE commands within a batch file, drop into the command prompt and ener te command followedby question switch For example for /?or if. Yougetan onscreen heb fie detaing the commands se. For easier ean, pipe toa text fle For /? > forhelp. txt Coding with Windows 10 Batch Files Creating a Batch File Game Based on what you've looked at eT Uamey lee CCM ol Rea) Peete Runs tielTa PT Checoemere Ula c elma eel) (oom choice game. Here’s one that we face le te aN AUR elt he Bint -d ao) eee R elt meO Le ‘Make up your own questions buthow about also Including an introductory or loading screen? Make your loading screen in aseparate batch file and save it as screens bat (for example).Then, from the main game batch file, you can load itatthe beginning ofthe File with the ‘call command Followed by colour to reset the game's colours: echo off call screens.bat color vstart set /a score=0 set /a question=0 set /p nane= What is your name? wom ppublestionscom echo off cls set /a scos set /a questi cls sot /p name= What is your nane? els ‘echo. ‘echo coche. ‘echo Welcome thane! to the super-cool trivia gane ‘echo. ‘echo Press 1 to get started ‘echo Press 2 for instructions ‘echo. ‘echo Press Q to quit ‘echo. choice /c 120 Af errorlevel 3 goto :eof if errorlevel 2 goto Instructions cis ‘echo. ‘ecko. ‘echo The instructions are simple. Answer the questions correctly. ‘echo. ela goto menu sot /a questicnstquestiontt els af % e sstiont ==5 (goto end) else (echo you are on jon tquestiont) ‘echo. timeout /T 5 /nobreak > nul Af tquastiont ==5 (goto end) else (goto tquestiont) els ‘echo. ‘echo * ( Creating a Batch File Game el” echo Your current score is tscoret Af errorlevel 3 goto wrong echo. Af errorlevel 2 goto wrong cho Weteteneanneusaneannaannaneaye Af errorlevel 1 goto correct echo. echo. 4 fecho Question tquestiont, cls echo, ‘echo. ‘echo Which of the following version of Windows is the ocho *wst#sesssavaevatensnnavavens best? ‘echo. echo. ‘echo Your current score is tscoret echo A. Windows 10 echo. == loco #teseteateatensnasnnenastenees echo B. Windows ME ‘echo. echo. ‘echo. echo C. Windows Vista ‘echo Question ¢questions. echo. ‘echo. choice /¢ abe ‘echo Which of the following Windows uses DirectX 127 Af errorlevel 3 goto wrong ‘echo. Af errorlevel 2 goto wrong ‘echo A. Windows 10 Af errorlevel 1 goto correct. ‘echo. ‘echo B. Windows 3.21 2 ‘echo. cls ‘echo C. Windows xP echo. ‘echo. echo. teteeteetsaisetateneanestnete (elsdoeT/CIaBa) echo. Af exzorlevel 3 goto weong echo Your current score is tscoret Af errorlevel 2 goto wrong echo. Af errorlevel 1 goto correct soho Ferestesteesnesterisesvesnests echo. sirong echo, cls fecho Question Squestiont. focho ‘#stennaneanennnas echo. ‘echo. fecho Which of the following version of Windows is the echo WRONG! most stable? ‘echo. echo. cho stetennensstenense fecho A. Windows 10 set /a score=tscoret-1 echo. pause echo B. Windows 95 goto game echo. fecho C. Windows ME soorrect echo. cls ‘Guokoe, /orabe] ocho stestanensenenenss Af errorlevel 3 goto wrong ‘echo. Lf errorlevel 2 goto wrong ‘echo CORRECT. YIPEB!"! Af errorlevel 1 goto correct echo. facho stesennenseneseass 3 set /a score=tscorot#1 als pause echo. goto game cho wetestestussueseeseesensenetee echo. rend echo Your current score is tscoret cls echo. cho sHtteeneesetentnanenensatenent echo Wetestentenaneseasanannanesee ‘echo. echo. ‘echo Well done, tnanot, you have answered all the echo. questions fecho Question Squestiont, echo. echo. ‘echo And your final score 4s fecho Which of the following Windows version is the ‘echo. latest? ‘echo Sacoret echo. ‘echo. sale MeO (ocho. senetavarsesnessesavatseunsneny echo. choice /M ‘play again? ¥/X" echo B. Windows 98 Af exzorlevel 2 goto eof echo, if errorlevel 1 goto start echo C. Windows 7 echo. choice /C abe Ae tt Taso et 779 PA) Nm ment htt | Ld A 7 iy chon (a a | 08 _ | Coding maro)ny miniun. Tee eee ec csy both malleable and powerful, while offering Ce ee cae which to build their skills. While all the popular and mainstream programming languages are BT ee En se eee Un: oa EO ur emer eM een uP Mel Ceres Coat i Re eek eee cL Pecan tite heed interact with the user, or simply work in the Pe ee tuner cane ee nce STAID ee oR Be NR Secor ann ST Pea Nt iter ec aa Ceuta ie i =a | a Ea 23 SY Coding on Linux ) Why Linux? FREE AND OPEN Linux isa fantastic fit for those who want something different; the efficiency of the system, the availability of applications and its stability, are just a Few reasons why. ‘The Firs thing we need to adéresss that there isno basic operating system called Linux. Fundamentally, Linuxis the operating system kernel, the core component of an OS. When talking about Linux we are infact, eferring to one ofthe mary distrbutions, or dstros, that use the Linux kernel, No doubt you've heard ofa east one of the current popular distro: Ubuntu, Linux Min, Fedora, openSUSE, Debian, Raspbian... the lst goes on. Each one ofthese distros offers the user something alittle different. While each has the Linux kernel at itscore, they oer a different looking desktop environment, different preloaded applications, different waysin which to update the system ‘and get more apps installed anda slightly different ook and Feel throughout the entire system. However, a the centrelies Linux, which iswhy we say, Linux. Linuxis a great operating system in ) which to start coding. aoa xeojas BOB * Senn eecem Linux works very ciffeently to Windows or macOS. Fora stat, ts Free to download, ree to install onas many computers as you lik, Free to use for an unlimited amount of time and fee to upgrade and extend with equally free programs and applications. This free to Use element is one ofthe biggest draws fr the developer. While a Windows license can cost upto £100 and a Mac considerably more, user, be they a developer, gamer, or someone who wants to put an ‘older computer to use, can quickly download a distro and get to work in amatter of minutes. Alongside the free to use aspect comes level of freedom to customise and mould the system to your own uses. Each ofthe distros available on the internet have certain ‘spin, some offer increased security, a fancy looking desktop, a gaming specific spin or something directed toward students. This extensibility makes Linux a more desirable platform to tse, a5 you can quickly mould the system intoa development base, including mary different kinds of IDEs for use with Python, web development, +, Jave and so 0n, or evena base for online anonymity, perhaps.as a Minecraft serve, media centre and much more. ‘Another remarkable advantage for those looking to learn how to code isthat Linux comes with most ofthe popular coding environments builtin. Both Python and Ce+ are pre-installed in high percentage of Linux lstros, which means you can stat to program almost as soon as, you instal the system and boot ie up for the Frsttime. Generally speaking, Linux doesn't take up as many system resources as Windows or macOS, (by system resources, we mean memory, hard drive space and CPU load), asthe Linux code has been streamlined andis ree from third-party ‘bloatware’, which hogs those systems resources. A mare efficient system, means more available resources forthe coding and testing environment and the programs you will eventually create. Less resource use also means, you can use Linuxon older hardware that would normally struggle, ‘or even refuse to run, the latest versions of Windows or macOS, A ‘There are thousands of free packages 6) available For programmers under Linux. ~ Why Linux? a ® @ ubuntu on QO Mandriva debian slackware A Each distro offers something unique to the 2-2 user but allhave Linux at the core. So rather than throwing away an old computer, itcan be reused with aLinuxdistr, However itsnat.all about C++, Python, or any ofthe other more popular programming languages. Using the command ine of Linux {also called the Terminal, you're able to create Shell scripts, which are programs made up of scintng languages and designed to run from the command line. They are used mainly a automate tasks, or offer the User some Form of input and output fora certain operation. ‘There are many more advantages we could list, For example, there are thousands and thousands of Free programsand apps available that cover practically every aspect of computing, Known as packages, there ae (atthe time of writing) over 8,700 spectic programming applications on Linux Mint alone and an incredible 62,000+ overall packages, catering from Amateur Radio to WWW tools. In conclusion, Linuxisa great resource and environmentin which to program. t's perfectly suited for developers, while continually improving and evolving, IF you're serious about getting into coding, or youjustwantto explore something new, then give Linuxa try and see how eworks for you. A Linux programming environment can be as simple or as complex as you need it tobe. The Best Linux leh Distributions ) By far the most popular Linux distro (distribution) is Linux Mint. In factt's recommended that you spend at least some time trying ‘Mint began ife backin 2006, as an alternative to the then, most ___ different environments and even different distros, to see which Potente ict ec rate tthe) cee ete et eased ert mt eee ee eens pete ees Ce ee eee ene peta ed te rc ney atfirst, but it’s quit simple, Currently, Linux Mint uses the Ce ee ore) eee CR ee aoe econ ses less Fancy graphics but is more stable on a wider variety of Cee heen er desktop environment thats built for speed and ultimate stabilty Se One ert Peet et es neat The second most popular distro available is Ubuntu: an ancient African word meaning ‘humanity to others’. Ubuntu's popularity has fluctuated over its Fourteen-year life. At one time, it was easily the most used, Linux-based operating system in the ee eee eer neg ee ea eet Te) controversial elements involving privacy, saw it topple from the pre Pe ae ec Pere eaeae eit) Moet eee oT) Peet ere ae eae MCR ey Meee eee ores the OS use the GNOME 3 desktop environment, i'simpressive experimenting with. tt’ a clean interface, easy to use and install although it can be alittle confusing For former Windows users _and offers the user the complete Linux experience. aR -aReHLNUKORE OS aan ‘rch s one ofthe longest running Linux distributions and Peete en) a een ee gen eter ec er ae ey Gee nantes ea Reese Coc Fe ee ease) Rice ee ce an software packages that will help you get started. CCR aS nu etka ce? OpenSUSE Leap isa rock-solid system. It’s developed openly bya community, along with SUSE employees. They develop Pen eee en rat eet London Stock Exchange, amongst other things. tis designed Ra oe ee ed for instabilty.f you find al that too sensible, openSUSE Se ee cr) Pree rancs ee eee eee ca ae een ee errs Ee eae een environments and use them as you would with any other distr. Ce ee eae rs ‘You start with nothing more than the command line and from Ree tee ee eS eo ee ea eee ey installa desktop environment, along with the apps you want. Cee ee ce Ly Reese enn cee oie eS eae eee ead Pee eee icons The advantage, for allthis hard work, ia distro that you've oe aa eC ae e eee eet ee eee eet asta Reese er neg eee eee Cero Ca ey taken the technology world by storm Preece ree different programming languages and educational resources. eeu ae) etal Peeeun eenyoras Sn ene eer aes Cee tre Dread Cae ed ce eer ea) err eeary petri r at ae Aswith the Pi version, Raspberry Pi Sn er outa ey eee Re cea measuring not much bigger than a creditcard, You can employ educational and other apps you will ever need. It's quick, stable itto build electronics, using a fully programmable interface and and works superbly. If you're interested in stretching your itcomes with Raspbian, its own custom-made, Debian-based _Linux experience, then this is definitely one of the top distros ee eee te ee eee ee =a Coding on Linux ) Equipment You Will Need MINTY INGREDIENTS Here's what you'll need to install and run Linux Mint as we work through this book. You have several choices available, so take your time and see which works best For you. : ‘The minimum system requirements For Linux Mint are as Follows: cru 7ooMHz RAM si2Me Hard Drive Space 968 2068 recommended) Monitor 1024x768 resolution F Obviously the better the ystem youhove thebetterand quicker = E the experience will be, You caninstall Linux Mint onto your computer via USB or DVD. Welllookinto each alittle later on, but youre already familiar with the process (or you're thinking of USB and just ‘gathering the hardware you'll need), then you're going to ‘eed a minimum 4G8 USB flash drve/stick to contain the Linux Mint 150, wom ppublestionscon V0 installation of Linux Mint simply requires a blank OVD-R disc. OF course, youl also need an optical drive (a DVD Writer drive) before you'r able to transfer, or bur, the ISOimage to thecisc. Installation toa virtual environment i a Favourite method of testing and using Linux distros. Linux Mint works exceedingly well when used ina vrwal environment, more on that later, There are many different virtual environment apps availabe, however VirtualBox, From Oracle, is one of the easiest. You can get the latest version From wwrw.virtvalbox.org, ¥F VirtualBox Equipment You Will Need Iegoes without saying that an Internet connection is vital for making sure that Linux Mint is resourced with the latest updates and patches, as well asthe installation of further software. Although you dont need an Internet connection to Use Linux Mint, you'l miss out on a wortd of free software available forthe distro, ‘Although Linux Mint can be installed onto a Mac, there'sa school of thought that recommends Mac owners usea virtual environment, such as VirtualBox or Parallels and why nat, rmacOSis already a splendid operating system. I you're looking tobbreathe new life into an older Mac, make sure it's an Intet CPU model and not the Power-PC madels. However, be aware, it’s nat as painfree as installing on to aPC. wn pcpubliestionseam Creating a Linux Installer on Windows You need to transfer the downloaded Linux ISO to either a DVD or a USB key before Meese cm elec A Cua Claret) test the OS prior to installation, but First you need to create the bootable media. DVD BOOTABLE MEDIA We're using a Windows 10 PC here to transfer the ISO to a DVD. As long as you're using a version of Windows from 7 onward, the process is extremely easy. Fret cate theSO mage of Lins area Sud? downloaded. in Windows 7, 8.1 and 10 computers, youl sul fnd hist Downlonds folder nes, when save you've spectieda diferent location, % Quicksccert Fwamint18.1-innamon- 6868 3 Dropbox (eam BOM) Onedive Si twerc © coovive (esate & Nework fightclickthe Linx $0 and fom the menu select SAPS Burn Disc Image. Depending on the speed of the PC, irmay ae a few secondsbefore anything happens, Oo worry too muh unesitakesmorethana minute in whch ase might be worth restarting your PC and trying again, With uck, the Windows Disc Image Burner should launch, Mount Bum disc image EH] Scan with Windows Defender.. Share Open with BS Open with WinRAR BD Addto archive SP bddtn "i rmint=10 tarinnaman-Adhit 1 PETITE DD Next insert recordable DVD disc into your computer's optical drive. After afew seconds, while the disci read, windows wil display a pop-up message asking you ‘what to do with the newiy inserted disc, ignore thisas we're going touse the builtin image burning Function PEPTIP DD withthe windows Disc image Burner dialogue box ‘open, click on the ‘Verify disc after burning’ tick box, followed by the Burn button. The process should take a Few minutes, depending on the speed of your PC's optical drive. Once ies complete, it will un through the verification stage and when done, the optical drive should auto-eject the dsc For you. USB BOOTABLE MEDIA USB media is Faster than a DVD and it’s often more convenient as most modern PCs don't have an optical drive installed. The process of transferring the images easy, but you'll need a thi Creating a Linux Installer on Windows ea ird-party app first and a USB flash drive of 4GB or more. ua Drive Properties First openupaweb |S csrmarsba 3 browserandgoto | gama https://rufus.akeo. een 1 tog ttn, 3 © (immer faf-Scol downthe | ramos ‘ym pagealitieandyout | St =) tibet come to a Download See ie heading, under which | Amat Options youlise th latest version of Rufus ee a Left-lick on thelinkto | “=e | _ (aebeseetenie =| start the download. Scania lane Satve — a a [oe BETTER wren you're ready, click on the Start button at the bottom of the Rufus app. Thismay open up another dialogue box asking you to download and use @ new version (of SysLinux. SysLinuxisa selection of boot loaders used to allowa ‘modern PC to access and boot from a USS Fash drive. Itis necessary, soif asked, click on Yes'to continue. “This image ves Syn 6.03/20151222 but this ppition only includes the instaloon fies or Sysinax 03/2014 1008 ‘As new versions of Sina are not compile with one anther, anit ‘would be possible for Rufus to ncude ther lwo atonal fee ‘must be downloaded fom the lnteme (linus and linus) Talc Verto connect to the ote! and dowrloed theses 1 Select Noto cane the operation Note: Theis willbe downloaded inthe cuent appiation detory Es . Dave Properties Double-click the ome downloaded Rufus {mati imine 3 executable;youcen “Salaam ar click Yes tothe Eaneet oe Windows security - . ee ‘question and ‘Yes’ ae ae to checking for Format Options updates. With Rufus launched, it should have already identified your inserted USB Flash drive (iFnot, just remove and reinsert). ‘od willbe reed automatically present ‘The next step asks in which image mode do you ‘want the Linux SO to be written to the USB flash drive, Both methods work for different situations, but generally, the recommended ISO Image Made isthe more popular. Make sure this modeis pre-selected and click ‘OK’ to continve, followed by Ok’ again to confirm the action, Theimage you have lected ir an'SOFrid image. Thi means tan be ‘atten erin 8 mage Te copy) mode or DD image (Sk image) mode Fufrrecommengr ung SO magemmoce so that You senyhave fal Asta the ve ser wing Howeve you encounter nue ding bot yeu can ry wting hi mage ‘gain OO image ese Pease let the mode that you wat to ut write this image © Witein 80 mage mode Recommended) ‘wien D0 image mede OK | ane [Atfirstglance the Rufus interface can ook aittle confusing, don't worry though, it’ really quite simple. To begin with, cick onthe SELECT button next to the ‘Disk ‘SO Image (Please select pulldown menu. This wil launch a Windows Explorer window from where you can locate and select the Unux 0. a Faciaa Drive Properties Thetinux'SOisnow ee being transferred to o—e ae 3 the USB lash drive. The mitcmeassin 5) © [mr processshouldnttake ‘swnsame ex oolong, dependingon ME) tina the speed of the USB nial device andthe P, During Fomat options the process youmay find [esiernicnmnsese Rufuswil auto-open the sme — USB divein windows SE Sahm oe sa if you wane ekon the mor Close buttononcethe go = oe pracess is complete, SY Coding on Linux Installing Linux on a PC UEFI BIOS The Unified Extensible Firmware InterFace (UEFI) is used to identify hardware and protect a PC during its boot-up process. It replaces the traditional BIOS, but can cause issues when installing Linux. Insert your DVD or USE Flash drive into your PC and, fou haven't already, shutdown Windows. In this ser instance, we're using the USB boot media but the processis virtually identical. Start the PC and when prompted press the appropriate keys to enter the BIOS or SETUP; these could be, for example, 2, Del or even F12, PRTTIPDD there arecifferent versions of a UEFI BIOS, so covering them all would be impossible, What you're looking for ia section that details the Boot Sequence or Boot Mode. Here you'll have the option to turn off UEFIand choose Legacy, or cisable Secure Booting. Most distros work with UEFI but itcan bea tricky process to enable ito boot. PEED) With uEFitumed to Legacy made, there are now two ways of boating into the Live Environment Firsts via the BIOS you're already in, Locate the Boot Sequence and change the first boot device fram its oxiginal setting, usually Internal HOD or similar, to: USB Storage Device for the USB media option; or VO Drive, for the DVD media option. a erty ead een nnn Pee a Peron a ee amen PAID 2ternativety use the Boot Option Menu. With this, option, you can press F12 (or something similar) to display lst of boot media options; from there, you can choose the appropriate boot media. ither way, you can now Save and Exit the BIOS by navigating to the Save & Exit option and choosing Save Changes and Exit. Network boot from AMD An?9CI70A sHard Drive +Renovable Devices Network boot from AMD fm?9C370A #2 Installing Linux ona PC Edeg INSTALLING LINUX (Once the Live Environment has booted, you will see the option to install the distro to your computer. Have a look around and when you're ready, look for the Install option on the desktop. ESTER cvicing you're connected to the internet (Frnt FSFP DD before the instalation process begins, you're asked then doo now) and you're inthe Live Environment, if the choice you made regarding the erasure of the stallation pracess by doubleicking onthe installLinux hard drive This is your last chance to back out. IFyou're stroswilldisplay theirown name, of certain you don't mind wiping everything and starting again with ickContinue when you're ready. Linux Mint, click Continue, If youneed to back up your files remove the Linux disc/USB, reboot, back up and start again. Wie enwatcenpcssiinysinixacos — EEEEI tray owt sete tp youn Sue most Linux distros, some offer different questions SEP 5 username and password. Enter your Name to begin duringthe instalation, Ceneraly, the questions are too iit or wth, then Computer Name -which the name sed olden tecnica bt some sichas"taling rapt soTtwae,canbe onthe network Next, choose a Username, flowed 2 good confsng in thiscae you cancick Continue but youre unsure, Password, You cantik the Lapin Automatically option, but lave have an internet connected device avalabletoaskanyquestons.” the Encrypt Home Folder option or no FERED When installing a new operating system's FTE The installation process can be quick and there may recommended that you wipe the old 05, replacing it ore questions to answer, ori may simply start with the new. When you reach this stage of the installation process, installing Linux based on your previous answers. Either way, you will ensure the ‘Erase disk andinstall Linux.” option isselected. NOTE: end up Being asked ta Continue Testing the Live Environment, or This will completely wipe Windows 10 From your computer; make Restarting to use the newly installed OS. If you're ready to use Linux, sure you have backups of all your personal files and data. then clck Restart Now. mppuistionscam Coding on Linux Installing a Virtual Environment GOING VIRTUAL Using a Virtual Machine (VM) will take resources from your computer: memory, hard drive space, processor usage and so on. So make sure you've got enough of each before commencing. Weresngvitisoxinbisisin astsonect EEERRER vente oe pctages donne fre Sur il the easiest virtual environments to get to grips with. S895) ‘we install anything, we need to make sure that the Enter wmwitualboxorg and clckon DownlosdVitualBor. Ths computer youre using [ble these VM, Todo this reboot the wi tae you tothe main dovnload page, ocatethe corecthost computer and enter the BOS. Asthe compute startup press the for yoursystem: Windows or Mac the Host isthe current installed Del, F2, or whichever key is necessary to Enter Setup, ‘operating system and click the link to begin the download. yg 7 VirtualBox ' rey cing et aera ie \ PEED Next, while still atthe VitualBoxdownload page, IAB As each ai0sisiaid out differently, it's very dif lacate the VirtualBox Extension Pack ink, The to.assess where tolook in each personal e Extension Pack supports USB devices, aswell asnumeraus other However, as ageneral rule of thumb, you're looking for Intel extras that can help make the VM environmentamoreaccurate _Virtualsation Technology, or simply Virtualisation, usualy within ‘emulation ofa real’ computer. the Advanced section ofthe BIOS. When you've located it, Enable it, = save the settings, ext the BIOS and reboot the computer. y ‘ualBox wom ppublestionscom ith the computer back up and running, locate the downloaded main VirtualBox application and double-click to begin the installation process. lick Next to continue, when you're ready. Boral ve Vrulbox6116 Setup * << ‘The default installation lacation of VirtualBox should satisfy most users, butf you have any special location requirements, click on the Browse’ button and change the install Folder. lso, make sure that all the iconsin the VirtualBox Feature tree are selected and none of them have a red X next to them. Click Next to move on, Chante arent recon ochre ny etre bee S| weabon ) asereaes nS ones safeties a = — = a “Thssectioncan beleftothe defaults, should you Guay wish. It simply makes life a little easier when dealing ‘with VMs, especialy when dealing with downloaded VMs, as you may encounter in the future. Again, clicking Next will move you on tothe next stage. cestom Setup Pee dees tam eer este stetnensenres oene a srtaten ie deatan estes atin te quckineds ar (Caper scat C Installing a Virtual Environment ea” ‘When installing VirtualBox, your network connection will be disabled For a very brieF period. This is due to VirtualBox creating alinked, virtual network connection so that any VM installed will be able to access the Internet and your home network resources, via the computer's, already established, network connection, Click Yes, then, instal to begin the installation at} Warning: Network Interfaces beige race tbo shetcrng Secedreet perro omecon odo You'll probably be asked by Windows to accept a security notification, click Yes fortis and next ‘you may encounter dialogue box asking you to trust the installation from Oracle, again, click yes and accept the installation ofthe VirtualBox application. When it's complete, cick finish to start VirtualBox. SB seer once son 6.136 te rtaton With VirtualBox up and running, you can now install the VirtualBox Extension Pack. Locate the downloaded ad¢-on and double-click. There may be ashort pause ‘while VitualBox analyses the pack, butyou'll eventually receive 3 ‘message to install it; lick install to begin the process, scroll down the next screen to accept the agreement and clck'l Agree’. VirtualBox - Information The extension pack Oracle VM VirtualBox Extension Pz was installed successfully. OK EP Coding on Linux Installing Linux ina Virtual Environment itera eA netll sree AU ROME aba a eke t ct A et S VES ue nucnacn ae Uaee ent mer een ne tices Motmetre emus el Recipe UMC AUER SEN ceiseaceesd CREATING THE VM There are plenty of options to choose from when creé excellent Linux Mint, and perform well. a VM. For now though, welll setup a VM adequate to run the FERED With vitwalB0x open, cickon the New coninthe — EREESEM The next section wil define the amount of system top-middle ofthe right-hand panel of the app. This memory, o¢ RAM, the VM hasallocated. Remember will pen the new VM Wizard, this amount willbe taken from the available memory installed in your computer, so dont give the VM too much. For example, we have 868 of memory installed and we're giving 2G8 (208M) to the VM. when you're ready, click Next to continue PESPD 0 the box next to Name type Linux Mint, and FETED Thissectionis where youll start to create the virtual VirtualBox should automaticaly choose Linux as hard disk that the VM will use to install Mint onto. the Type and Ubuntu (64-bit) asthe Version, iFnot then use the The default option, ‘Create avirtualhard disk now, isthe one we're {drop-down boxes to select the correct settings (remember Mint using. Click Create to move on. mainstream is based on Ubuntu). Click Next when you're ready to proceed, Installing Linux in a Virtual Environment [ Thepopupwindow thatappearsatercicking RUMI fer cidking Create the il setup ofthe Vis Creates asingyeu what pe of eather dk complete. youshuldnow be ooking atthe newly youwanttocreate were gol tose the GefautVOI(itualbox _ceatedVMuihinthe tutor aplcaon Seereyou bah euch Disk image) in this case, as the others are often used to move VMs_ click the Settings button From the top of the right-hand panel, and within from one VM application to the next. Make sure VDI is selected, and _ the General section click the Advanced tab. Using the pull-down menus, iNest choose Bereta fr both Shared Clipboard andDragibvon an PRPIIPR the question of whether to apt For Dynamically or PPI rolw that by clicking on the System section, Fhredsized virtual hard disks may come across as being then the Processor tab. Depending on your CPU somewhat confusing tothe newcomer. Basically, a ynamically Allocated allocate as many cores as you can without detriment to your host vetualhard dskis a more flexible storage management option. tworit system; we've opted for two CPUs. Now click on the Display section, take up machspace within your physicalhard dskto beginwith ether. side the Video Memory up to the maximum, and tick ‘Enable 3D Ensure Dynamically Allocated s selected, and click Next, ‘Acceleration’ Click OK to commit the newsettings. FTG RAD The virtual hard disk willbe asingle Folder, upto the [ENESSETRIM Click on the Start button and use the explorer size you state inthis section, button in the ‘Select Startup Disk’ window; the Ensure the location ofthe virtual hard disk, on your computer, has explorer button isa folder with a green arrow. Click Add in the new ‘enough free space available. For example, we've used a bigger pop-up window, to lacate the downloaded ISO of Mint; and click storage option on our O:\ drive, namedit Linux Mint, and allocated Opento select the ISO. Now click the Start button to boot the VM 25.50GB of space to the virtual hard disk ‘withthe Linux Mine Live Environment. You can now install Linux as per the standard PC installation requirements we Coding on Linux.) Getting Ready to Code in Linux TAKING COMMAND ‘The command line is at the core of Linux and when you program with it, this is called scripting, These are self-contained programs designed to be run in the Terminal Therese oubesinourauney —— ERRERER) wat soucsrety san te einai og sua? with Linux, through the command line and thus sa? name followed by the name of the computer, as you ‘any criting from. in Linux Mint, Itcan be accessed by licking on __namedit when you firstinstaled the OS on to the computer. The the Menu Followed by the Terminalicon inthe panel, or entering _ ne then ends with the current folder name; at Fist this s justa tilde "Terminal into the search bar (), which means your Home Folder david@david-mint ce Cee [pees Box BB ove FETED The Terminal will give you access tothe Linux PPM the Flashing cursorat the very end ofthe line is Mint Shel called BASH; this ives you access to where your text based commands will be entered. the underlying operating system, which iswhy scripting issuch a _-Youcan begin to experiment with a simple command, Pint Working powerful language to learn and use. Everything in Mint, and Linux Directory (pwd), which will output to the screen the current folder ‘as a whole, including the desktop and GUI, isa madule running from you'e in. Type: pd and press Enter. the command ine, Fleet Ven Search Terminal Help Senet File Et View Search Terminal Help wom ppublestionscom FETED lithe commands you enter will work in the same ‘manner. Youenter the command, include any parameters to extend the use of the command and press Enterto ‘execute the command line you've entered, Now type: uname ~ ‘and press Enter. This will display information regarding Linux Mint, In scripting, you can use all the Linux command-line commands within your own script. File Edit View Search Terminal Help St) emer nec estas) Ce HERE BE DRAGONS! (_ Getting Ready to Code in Linux gee BETISTD The list of avaliable Linux commands is vast, with some simply returning the current working directory, while others are capable of deleting the entire system in aninstant. Getting to know the commands is part of learning how to script, By using the wrong command, you could end up wiping your computer. Type compgen =< to view the available commands, Fle Est View Search Terminal Help ‘There's an urban myth on the Internet that an employee at Disney Pixar nearly ruined the animated movie Toy Story by inadvertently entering the wrong Linux command and deleting the entire system the film was stored on. Having accessto the Terminal means you're bypassing the GUI desktop method of working withthe system, The Terminals afar more powerful environment than the desktop, which has several safeguards in place in case you _accidentally delete all your work, such as Rubbish Bin to recover, deleted files. Therefore ts always a good idea to work nthe Terminal using a two-pronged approach. Fist, use the desktop to make regular backups of the Folders you're working in when in the Terminal. This way, should anything go wrong, there's a quick and handy backup waiting for you. However the Terminal doer fer that ox Sire “you were to access a Folder with Files within via the Terminal and then enter the command: rm *.., athe Filesin that Folder would be instantly deleted. They won't appearin the Rubbish Bin either, they're gone For good david@david-mint ~/Mi File Edit View Search Terminal Help PPI second, research before blindly enteringa ‘command you've seen an the Intemet. Fyousee the command: sudo dd if=/dev/random of=/dev/sda and use iein a script, you'lsoon come to regret the action as the command will wipe the entire hard drive and fill it with random data. Take a ‘moment to Google the command and see what it does. Google «t=mnne amen e mpcpubistionscam Coding on Linux ) Creating Bash Scripts —Part 1 GET SCRIPTING ‘ABBash script is simply a series of commands that Mint will run through to complete a certain task. They can be simple or remarkably complex, itall depends on the situation. Fle St View Search Terinal_ Help File ES View Search Teminal_Help FTPD there areseveral text editors wecanuseto create [IAB windows users willbe aware that in order Fora a Bash script: Xed, Vi, Nano, Vim, GNU Emacs and batch file to work, as in be executed and fallow the 0 0n. Inthe end itll comes down to personal preference. Our programming withinit, it needs to have a BAT file extension, Linux. use of Xed is purely due to making Iteasier to read the scriptin the isan extension-ess operating system but the convention's to give screenshots you see below. scriptsa sh extension, Fle at View Search Terma Hep wom ppublestionscom Let’ start with a simple script to output something tothe Terminal. Enter xed helloworld. eh, ‘This will aunch Xed and create afilecaled helloworld.sh In Xed, center the following: ##/bin/bash, then on a newline: echo Fle de View Search Terminal He Fle Edt View Search Tools Documents Help poaln~|/xyo0 ag alloweiish os /osn/bash echo Helte Worts! The #1/bin/baat line tells the systern what Shell. you're going to be using, in this case Bash. The hash (@ denotes a comment line, one thatisignored by the system, the ‘exclamation mark () means that the comment is bypassed and will Force the script to execute the line as a command. This s also known as aHashBang, poalnv|yoojaga #1 bin/bash FERED Youcan save ths le, clicking File> Save, and ext back to the Terminal. Entering 1, wil reveal the script inthe Folder. To make any script executable, and able to run, youneed to modify its permissions. Do this with chmod 4 sh. Youneed to do this with every script you create. hellowarld (_ Creating Bash Scripts-Part1 Epa SPP ines you ener 1 aan, youcansee thatthe S27 helloworld.sh script has now turned from being white to gee, meaning tatitsnon an erecatbl fle To un thescrbe mather words make othe things youve ped no, enter: . helloworld. sh, Fleet View Seach Terminal Help BEPTED 2tchoush it's not terribly excting, the words ‘Hello World’ should now be displayed in the Terminal The echo commands responsible for outputting the words after, iein the Terminal, s we move on you can make the echo command output to other sources. Fle Et View Search Tools Documents Help Doalny xooag (x howerdsh > 1 /binbash echo Hello World! This is ay first seript 4m Linux mi Think of echo as the old BASIC Print command. It clsplays either text, numbers or any variables that are storedin the system, such as the current system date. Try this example: echo Hello World! Today is $(date +8A).The (date +9) is calling the system variable that stores the current day of the week. BRED /dev/oull ) 11; thee When executed the script waits forinput from the User, n this case the file extension, such asp, mp4 and so on I's not very friendly though. Let's make it litle friendlier. Add an echo, with: echo ~n. “Please extension of the file you're looking for: *,just before the read command eR eT Here's an interesting, Fun kind of script using the app espeak. Install espeak with sudo apt-get Sar ea, then enter the text below into anew script called ‘speak.sh. Asyou can see it’s rehash of the First greeting script ‘we ran. Only this time, it uses the variablesin the espeak output, Sd output For our scripts. Whilst t's too long to dig a little deeper into the colour options, here's a script that outputs what's available. Create a new script called ish and enter the text (see below) into \We briefly looked at putting some coloursin the ( Creating Bash Scripts—Parts Ips The ouput from colours ano course, be sya mixed together, bringing different effects: depending on whatyou wantto te autut tsa, Preamp wht etna red backround ashing (or binking). Scythe Binking effec does wor onal Terminal, soyoumay need to change toa dferent Terminal Poet hist we're on making fancy scripts, how about using Zenity to outputa graphical interface? ah. Make it Enter what you see below into anew seri, mens ‘executable and then run it. You should have a couple of dialogue boxes appear, Followed by a final message. le gaming ina Bash script somethin BLM hs cen touched upon, tisentrel posable, abet, lite base Moverencbased games ae afl, and sometes busay, however good tert adventre or Fghtng Fantasy type game isa perfec choie for gaming inthe Terminal Shelta go, and et us ow Row you get on mpcipubistionscam Coding on Linux ] Command Line Quick Reference TOP 10 COMMANDS ‘These may not be the most common commands used by everyone but they will certainly Feature frequently For many users of Linux and the command line, he ca commandis one ofthe commands you The ny command moves file toa different will use the most t the command line in Linux location or renames a file. For example nv file allows you to change your working directory. You ub renames the orginal fileto sub. mv su use it to move around within the hierarchy of your Desktop mi le‘sub’ to your desktop file system. You can also use chdir directory but does not rename It. You must specify anew filename to rename aie, he 1s command shows you the flles in you The chown command changes the user a current directory, Used with certain options, it ets ‘or group ownership of each given file, only an Yyou se file sizes, when files where created and file ‘owner (a user name or numeric user ID)is given, permissions. For example, 1 ~ shows you the files that user is made the owner of each given file, and hat ae in your home diectory the files’ group isnot changed, ‘The ep command is used to make copies of iles The chitoa command changes the permissions on and directories. For example, ep file ub makes the files listed, Permissions are based on a fairly anexact ame you entered simple model. You can set permissions For user, ‘and names the copy sub but the fist ile will still ‘group and world and you ‘exist with ts original name. read, write and or execute the fle. ve pwe command prints the Full pathname of The xm command removes (deletes) files o the current working directory (pwd stands Fo directories. The removal process unlinks a filename print working directory’), Note that the GNOME in filesystem From data on the storage device erminal also displays this information inthe title and marks that space as usable by Future writes, In bar of ts window, ‘other words, removing files increases the amount of available space on your disk The clear command c this is possible. It looks inthe environment for the erminfo database Forexample, een, This iikair work directory. More than ping Control-L when using the tone directory may be specified when calling mkdir. rs your em, iFthe specified figure out how to clear equivalent to| bash shell wom ppublestionscon Cyr NER ACT} USEFUL HELP/INFO COMMANDS. Br uae eee ‘you are trying to learn more about the system or ene uhm etn Ce ue ek asst me Soret es ‘The EERE command displays the total amount Cees se ene emer ree nie eee Bs: eae eed Cm reuue ania s bp cues reece) tie rere rier en ecm eed Pee aCe ert Cicect “The MEMES command with the Bj option prints A meee Gee tg ale Bispace et eat Creer Pee ears! Bila crhe Eee ety ee eee ed a eo ceo soe Eee ere geet etd epee oe ceauets ees ‘The ERIM command adds anew user tothe system, Similarly, the EEETRRAME command adds 3 Cris erry Bic user eee ee ear Serre eerste eric) emcee eects conve] TE ootion. ‘The RETETEAM command removes group from Cer rer ae esd Cer ene. ‘The HEMMENEM command brings up the manwal entry For the man command, which isa great place Pecos Ts The SENUEEIEN commands especialty useful Deere tert eigen net Sree Rainey ics Ea

You might also like