特殊:Badtitle/NS100:Beginners/BashScripting:修订间差异
小 新页面: {{From|https://help.ubuntu.com/community/Beginners/BashScripting}} {{Languages|UbuntuHelp:Beginners/BashScripting}} Bash scripting is one of the easiest types of scripting to learn, and i... |
小无编辑摘要 |
||
第2行: | 第2行: | ||
{{Languages|UbuntuHelp:Beginners/BashScripting}} | {{Languages|UbuntuHelp:Beginners/BashScripting}} | ||
Bash scripting is one of the easiest types of scripting to learn, and is best compared to Windows Batch scripting. Bash is very flexible, and has many advanced features that you won't see in batch scripts. | Bash scripting is one of the easiest types of scripting to learn, and is best compared to Windows Batch scripting. Bash is very flexible, and has many advanced features that you won't see in batch scripts. | ||
However if you are a 'non-computer-savvy' person that won't mean a thing to you. Basically Bash is the language that you will learn to love, much of everyday Ubuntu life is done/can be done at the Terminal. You will soon learn that most things can be done through both gui (Graphical User Interface (visual programs)) and cli (Command Line Interface), however some things are more easily achieved from one or the other. For example, changing file permissions of a folder and all its sub folders is more easily achieved from cli then gui. | |||
== Intro == | == Intro == | ||
In this document we will discuss useful everyday commands, as well as going a bit more in depth into scripting and semi-advanced features of Bash. | |||
Bash is not only used to run programs and applications, but it can also be used to write programs or scripts. | |||
== Bash -- Everyday Ubuntu life == | |||
During your time as an Ubuntu'er you will use the terminal to perform tasks such as | |||
* Creating folders | |||
* Deleting files | |||
* Deleting folders and their sub-folders | |||
* Opening applications as root | |||
* Backing up your files | |||
* Backing up your folders | |||
* Checking system performance | |||
* Check Devices | |||
* Checking wireless connection | |||
And many other things, the list above will be the commands we will discuss. | |||
== Commands == | |||
=== Creating folders === | |||
Creating folders can be done simply in the file manager nautilus by right clicking and selecting 'Create Folder', but if you want to do this from a cli environment you would type the following in the terminal: | |||
<pre><nowiki> | <pre><nowiki> | ||
# | sudo mkdir /home/joe/Desktop/new_folder | ||
</nowiki></pre> | |||
the ''mkdir'' (make directory) command creates the folder then the file path tells it where to create the folder. | |||
echo "Hello World | (I use ''sudo'' because if you try to create a folder anywhere other then /home or one of its sub-directories you will need root/superuser privileges. This goes for all commands in this section.) | ||
=== Deleting files === | |||
# | Deleting files can be done like this | ||
<pre><nowiki> | |||
sudo rm /home/joe/file_to_be_deleted | |||
</nowiki></pre> | |||
the ''rm'' (remove) command is used to remove anything through a cli environment. | |||
=== Deleting folders and their sub-folders === | |||
The command you are about to read can potentially (if used incorrectly) '''destroy''' your system! | |||
<pre><nowiki> | |||
sudo rm -rf /home/joe/useless_Parent_folder | |||
</nowiki></pre> | |||
This command is slightly different to the one before, it uses two options '-r' which means recursive (will delete the folder and all sub-folders) and '-f' means force (will not ask for your permission). This command is perfectly fine for deleting a dir and all its sub-dirs. The next commands should '''!!**!!NEVER!!**!!''' be run. Unless you want to say goodbye to your system. | |||
<pre><nowiki> | |||
sudo rm -rf /* | |||
sudo rm -rf / | |||
</nowiki></pre> | |||
This will delete everything from your root folder downwards, which if you did a standard install would be '''everything'''. | |||
=== Opening applications as root === | |||
Sometimes you will want to edit a config file in your root folder, in order to save changes to this file you need root privileges so we need to open our text editor as root. (assuming your text editor is gedit) | |||
<pre><nowiki> | |||
gksudo gedit /path/to/conf_file.txt | |||
</nowiki></pre> | |||
''gksudo'' is the same as ''sudo'' only it brings a box up to ask for your password, ''gksudo'' should always be used to open graphical applications as root. | |||
Serious damage can be done to your system by editing these files. It is advised to create a backup of any file you edit. | |||
=== Backing up your files === | |||
To create a backup of a file, we're going to use the ''cp'' (copy) command. The basic syntax for ''cp'' is as follows: | |||
<pre><nowiki> | |||
cp source_file dest_file | |||
</nowiki></pre> | |||
This will copy the 'source_file' to the 'dest_file'. Now, using the previous example, we want to backup '/path/to/conf_file.txt'. To accomplish this, we type the following: | |||
<pre><nowiki> | |||
sudo cp /path/to/conf_file.txt /path/to/conf_file.txt.old | |||
</nowiki></pre> | |||
That's fine and dandy, but what if I want to copy my file to another directory? Well that's just as easy. Let's say instead of copying /path/to/conf_file.txt to the /path/to/ directory, you want to copy it to a directory where you store all of your backup files, say /my/backup/folder/. In order to accomplish this you would type: | |||
<pre><nowiki> | |||
sudo cp /path/to/conf_file.txt /my/backup/folder/ #saves conf_file.txt to /my/backup/folder/ | |||
#OR | |||
sudo cp /path/to/conf_file.txt /my/backup/folder/conf_file_new_name.txt | |||
</nowiki></pre> | |||
***This is a typical safety measure that has saved many users in the past from a complete disaster.*** | |||
Okay, so we know how to copy a file a) to a different filename and b) to a different folder. But how do we copy entire directories? | |||
=== Backing up your directories === | |||
To backup one directory to another, we introduce ''cp''s '-r' (recursive) option. The basic syntax is as follow: | |||
<pre><nowiki> | |||
cp -r /directory/to/be/copied/ /where/to/copy/to/ | |||
</nowiki></pre> | |||
So if we wanted to copy all of the contents of our /path/to/ folder to our /my/backup/folder, we would type the following: | |||
<pre><nowiki> | |||
sudo cp -r /path/to/ /my/backup/folder/foldername #foldername can be whatever you want the foldername to be | |||
</nowiki></pre> | |||
=== Checking system performance === | |||
If your computer starts to lag, you can see which applications are using the most CPU power with this command: | |||
<pre><nowiki> | |||
top | |||
</nowiki></pre> | |||
This is generally the same information given as the GUI application 'System Monitor'. | |||
=== Check Devices === | |||
<u>USB Devices</u> | |||
If a USB device stops working, you may want to see if it is still connected/detected. To check if a device is connected/detected, type the following: | |||
<pre><nowiki> | |||
lsusb | |||
</nowiki></pre> | |||
<u>PCI Devices</u> | |||
PCI devices are checked with: | |||
<pre><nowiki> | |||
lspci | |||
</nowiki></pre> | |||
=== Checking wireless connection === | |||
To check the status on your wireless connection, use: | |||
<pre><nowiki> | |||
iwconfig | |||
</nowiki></pre> | |||
This also shows packets sent/received. | |||
== Scripting == | |||
Bash is primarily a scripting language, so it would be a crime not to talk about scripting. | |||
Let's dive straight in with a bash script. More precisely the infamous "Hello World" script. | |||
You can create a bash script by opening your favorite text-editor to edit your script and then saving it (typically the .sh file extension is used for your reference, but is not necessary. In our examples, we will be using the .sh extension). | |||
<pre><nowiki> | |||
#!/bin/bash | |||
echo "Hello, World" | |||
</nowiki></pre> | |||
The first line of the script just defines which interpreter to use. NOTE: There is no leading whitespace before #!/bin/bash. | |||
That's it, simple as that. To run a bash script you first have to have the correct file permissions. We do this with ''chmod'' (change mode) as follows: | |||
<pre><nowiki> | |||
sudo chmod 700 /where/i/saved/it/hello_world.sh #Gives read,write,execute permissions to the Owner | |||
# OR | |||
sudo chmod a+x /where/i/saved/it/hello_world.sh #Gives everyone execute permissions | |||
</nowiki></pre> | |||
This will give the file the appropriate permissions so that it can be executed. | |||
Now open a terminal and run the script like this: | |||
<pre><nowiki> | |||
/where/i/saved/it/hello_world.sh | |||
</nowiki></pre> | |||
Hopefully you should have seen it print Hello, World onto your screen. If so well done! That is your first Bash script. | |||
<u>TIP</u> | |||
If you type: | |||
<pre><nowiki> | |||
pwd | |||
</nowiki></pre> | |||
You will see the directory that you are currently working in (''pwd'' stands for 'print working directory'). If your current working directory is /where/i/saved/it/, then you can shorten the above command to: | |||
<pre><nowiki> | |||
prompt$ pwd | |||
/where/i/saved/it | |||
prompt$ ./hello_world.sh | |||
</nowiki></pre> | |||
Now, lets get to more interesting aspects of Bash programming, Variables! | |||
=== Variables === | |||
Variables store information basically. You set variables like this | |||
<pre><nowiki> | |||
var="FOO" | |||
</nowiki></pre> | |||
'var' can be anything you want as long as it doesn't begin with a number. "FOO" can be anything you want. | |||
To access the information from the variable you need to put a '$' in front of it like this: | |||
<pre><nowiki> | |||
var="FOO" | |||
echo $var | |||
</nowiki></pre> | |||
Try entering those lines into a terminal one at a time; you will see that the first one just gives you another prompt and the second one prints FOO. | |||
But that's all a bit boring. So let's make a script to ask the user for some information and then echo that information. | |||
<pre><nowiki> | |||
#!/bin/bash | |||
clear | |||
echo "Please enter your name" | |||
read name | |||
echo "Please enter your age" | |||
read age | |||
echo "Please enter your sex. Male/Female" | |||
read sex | |||
echo "So you're a $age year old $sex called $name" | |||
</nowiki></pre> | </nowiki></pre> | ||
''read'' allows the user to input information where it is then stored in the variable defined after the read. ''read variable'' would take whatever input the user entered and store it in $variable. We then access this with echo and set up a neat sentence. | |||
This script is reasonably messy though; read has another function that could halve the size of this script. | |||
<pre><nowiki> | <pre><nowiki> | ||
#! /bin/bash | |||
clear | |||
read -p "Please enter your name : " name | |||
read -p "Please enter your age : " age | |||
read -p "Please enter your sex. Male/Female : " sex | |||
echo "So you're a $age year old $sex called $name" | |||
</nowiki></pre> | </nowiki></pre> | ||
That is more efficient code. However it's still a bit messy when run. A solution? Good old white spaces! | |||
run | |||
<pre><nowiki> | <pre><nowiki> | ||
./ | #! /bin/bash | ||
clear | |||
read -p "Please enter your name : " name | |||
echo "" | |||
read -p "Please enter your age : " age | |||
echo "" | |||
read -p "Please enter your sex. Male/Female : " sex | |||
echo "" | |||
echo "So you're a $age year old $sex called $name" | |||
</nowiki></pre> | </nowiki></pre> | ||
Now we have an efficient and clean Bash script. | |||
=== If Statements === | |||
== | An if statement can be used to check for something and do something else depending on the outcome of the check. For example, if I had an 'apple', I would want to make sure it's still an 'apple' and not an 'orange' because I don't like Oranges! | ||
The syntax for an if statement is | |||
<pre><nowiki> | <pre><nowiki> | ||
if [something] | |||
then | |||
elif | |||
then | |||
elif | |||
then | |||
....etc.... | |||
else | |||
fi | |||
</nowiki></pre> | </nowiki></pre> | ||
The elif is not necessary, but it can be used if needed. | |||
An if statement to check if our $fruit variable is an 'apple' would look like this | |||
<pre><nowiki> | <pre><nowiki> | ||
if [ $fruit = apple ] | |||
then echo "Good, I like Apples" | |||
else echo "Oh no, I hate Oranges!" | |||
fi | |||
</nowiki></pre> | </nowiki></pre> | ||
Just to explain this statement, | |||
<pre><nowiki> | <pre><nowiki> | ||
if [ the contents of $fruit is 'apple' ] | |||
then say "Good, I like Apples" | |||
if it's not, then say "Oh no, I hate Oranges!" | |||
finish | |||
</nowiki></pre> | </nowiki></pre> | ||
the | If statements are an easy concept to grasp as they are similar to the "if" used in spoken English. But say you wanted to have 4 or 5 checks, the answer may be to write 4 or 5 statements but that's not the most practical way. This is where elif comes in handy. | ||
<pre><nowiki> | <pre><nowiki> | ||
if [ $fruit = apple ] | |||
then echo "Good, I like Apples" | |||
elif [ $fruit = pear ] | |||
then echo "Good, I like Pears" | |||
elif [ $fruit = banana ] | |||
then echo "Good, I like Bananas" | |||
else echo "Oh no, I hate Oranges!" | |||
fi | |||
</nowiki></pre> | </nowiki></pre> | ||
== Storing application stdout to a | This saves us from from repetitive scripting. There are better ways to check what the fruit is, but we won't go into that now. | ||
== Storing application stdout to a variable: == | |||
Application stdout ( what you see on the terminal screen, with an un-piped application ) can be saved and used in Bash. The simplest and most elegant way is to use the back-tick (`) this is not an apostrophe or quote (' or ") and is found on the same key as the tilde (~) | Application stdout ( what you see on the terminal screen, with an un-piped application ) can be saved and used in Bash. The simplest and most elegant way is to use the back-tick (`) this is not an apostrophe or quote (' or ") and is found on the same key as the tilde (~) | ||
=== Example === | === Example === | ||
第76行: | 第230行: | ||
</nowiki></pre> | </nowiki></pre> | ||
This code should output the current users, their respective ttys, and date of login. | This code should output the current users, their respective ttys, and date of login. | ||
Note that this strips newlines. Be sure to do any parsing in line ( | grep, etc ) then pass it to a | Note that this strips newlines. Be sure to do any parsing in line ( | grep, etc ) and then pass it to a variable. | ||
We will try this again, but grep for tty7, the GUI's tty. | We will try this again, but grep for tty7, the GUI's tty. | ||
=== Example 2 === | === Example 2 === | ||
第83行: | 第237行: | ||
echo $fooVar | echo $fooVar | ||
</nowiki></pre> | </nowiki></pre> | ||
This should output the single user that is currently logged | This should output the single user that is currently logged into the WM. | ||
Let's move on to more advanced data manipulation within back ticks. | |||
== FUNctions == | == FUNctions == | ||
Bash lets you create a function on the fly, really handy if you plan on using a code block more then once. Functions reduce the amounts of editing you have to do in a script, if and when you have to update your script. | Bash lets you create a function on the fly, really handy if you plan on using a code block more then once. Functions reduce the amounts of editing you have to do in a script, if and when you have to update your script. Let's get to it! | ||
=== Example === | === Example === | ||
Here is an example script: | Here is an example script: | ||
第114行: | 第268行: | ||
</nowiki></pre> | </nowiki></pre> | ||
This example, as you can see may be longer now, but | This example, as you can see may be longer now, but you can imagine how, adding features, this will eliminate code and reduce complexity. Also, you can see if you want to change the echo call, you have to edit one line, not two. | ||
==== Debugging ==== | ==== Debugging ==== | ||
I always find it useful to trace a script to find out why something does not work as expected. To trace start it trough bash explicitly and use the -x option, like so: | I always find it useful to trace a script to find out why something does not work as expected. To trace, start it trough bash explicitly and use the -x option, like so: | ||
<pre><nowiki> | <pre><nowiki> | ||
bash -x ./script.sh | bash -x ./script.sh | ||
第123行: | 第277行: | ||
== Other Scripting Languages related to Bash == | == Other Scripting Languages related to Bash == | ||
=== tr === | === tr === | ||
tr is one of the most basic applications to pipe data through that uses a basic scripting syntax. In this case, it accepts Regular Expressions. | ''tr'' is one of the most basic applications to pipe data through that uses a basic scripting syntax. In this case, it accepts Regular Expressions. Let's do a normally complicated task, transforming a string to all uppercase. | ||
==== Example ==== | ==== Example ==== | ||
<pre><nowiki> | <pre><nowiki> | ||
#!/bin/bash | #!/bin/bash | ||
read foo | read foo | ||
var=`echo $foo | tr "{a-z}" "{A-Z}" | var=`echo $foo | tr "{a-z}" "{A-Z}"` | ||
# {a-z} Matches a through z | # {a-z} Matches a through z | ||
# {A-Z} matches A through Z | # {A-Z} matches A through Z | ||
第138行: | 第292行: | ||
THIS IS A TEST | THIS IS A TEST | ||
</nowiki></pre> | </nowiki></pre> | ||
tr also can TRanslate strings, so | ''tr'' also can TRanslate strings, so let's translate all "tar" in $foo to "bar". | ||
==== Example ==== | ==== Example ==== | ||
<pre><nowiki> | <pre><nowiki> | ||
第152行: | 第306行: | ||
=== awk === | === awk === | ||
AWK ( Short for Aho, Weinberger & Kernighan ) | AWK ( Short for Aho, Weinberger & Kernighan ) | ||
awk has its own custom scripting language, suitable for a tutorial by | ''awk'' has its own custom scripting language, suitable for a tutorial by itself, so I will cover only the basics to help assist when you are bash scripting. This is not meant to be complete or comprehensive in any way. | ||
==== pidof clone ==== | ==== pidof clone ==== | ||
Let's make a quick pidof clone | Let's make a quick pidof clone that prompts for a process identifier, then echoes the process ID. | ||
<pre><nowiki> | <pre><nowiki> | ||
#!/bin/bash | #!/bin/bash | ||
read pname | read pname | ||
ps -ef | grep -v grep | grep $pname | awk '{print $ | ps -ef | grep -v grep | grep $pname | awk '{print $2}' | ||
</nowiki></pre> | </nowiki></pre> | ||
Single quotes are used to pass the ''awk'' command(s). The curly braces are to use the ''awk'' language (for stuff like prints, ifs, etc.). | |||
Print prints the column | ''Print'' prints the column passed given by the $ markup, space delimited. | ||
There | There are a lot more commands than the print command, including if statements, etc., and is worth looking into if you are interested in what you see here! | ||
=== sed === | === sed === | ||
sed is one of the most complicated scripting languages on the GNU / Linux system. I am only going to cover the s/ command here. | ''sed'' is one of the most complicated scripting languages on the GNU / Linux system. I am only going to cover the s/ command here. | ||
==== Basic Substitution ==== | ==== Basic Substitution ==== | ||
Try this out to show that sed can not only replace | Try this out to show that ''sed'' can not only replace inline, but unlike ''tr'', replace with a longer or shorter string than before. | ||
<pre><nowiki> | <pre><nowiki> | ||
#!/bin/bash | #!/bin/bash | ||
第172行: | 第326行: | ||
echo $foo | sed "s/foo/bars/" | echo $foo | sed "s/foo/bars/" | ||
</nowiki></pre> | </nowiki></pre> | ||
When this command is run, it should substitute | When this command is run, it should substitute the first appearance of "foo" with "bars". | ||
This is an example of the output. | This is an example of the output. | ||
<pre><nowiki> | <pre><nowiki> | ||
第178行: | 第332行: | ||
I love to go to bars | I love to go to bars | ||
</nowiki></pre> | </nowiki></pre> | ||
---- | |||
[[category:CategoryCommandLine]] | |||
[[category:UbuntuHelp]] | [[category:UbuntuHelp]] |
2008年10月19日 (日) 04:21的版本
文章出处: |
{{#if: | {{{2}}} | https://help.ubuntu.com/community/Beginners/BashScripting }} |
点击翻译: |
English {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/af | • {{#if: UbuntuHelp:Beginners/BashScripting|Afrikaans| [[::Beginners/BashScripting/af|Afrikaans]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/ar | • {{#if: UbuntuHelp:Beginners/BashScripting|العربية| [[::Beginners/BashScripting/ar|العربية]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/az | • {{#if: UbuntuHelp:Beginners/BashScripting|azərbaycanca| [[::Beginners/BashScripting/az|azərbaycanca]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/bcc | • {{#if: UbuntuHelp:Beginners/BashScripting|جهلسری بلوچی| [[::Beginners/BashScripting/bcc|جهلسری بلوچی]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/bg | • {{#if: UbuntuHelp:Beginners/BashScripting|български| [[::Beginners/BashScripting/bg|български]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/br | • {{#if: UbuntuHelp:Beginners/BashScripting|brezhoneg| [[::Beginners/BashScripting/br|brezhoneg]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/ca | • {{#if: UbuntuHelp:Beginners/BashScripting|català| [[::Beginners/BashScripting/ca|català]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/cs | • {{#if: UbuntuHelp:Beginners/BashScripting|čeština| [[::Beginners/BashScripting/cs|čeština]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/de | • {{#if: UbuntuHelp:Beginners/BashScripting|Deutsch| [[::Beginners/BashScripting/de|Deutsch]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/el | • {{#if: UbuntuHelp:Beginners/BashScripting|Ελληνικά| [[::Beginners/BashScripting/el|Ελληνικά]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/es | • {{#if: UbuntuHelp:Beginners/BashScripting|español| [[::Beginners/BashScripting/es|español]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/fa | • {{#if: UbuntuHelp:Beginners/BashScripting|فارسی| [[::Beginners/BashScripting/fa|فارسی]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/fi | • {{#if: UbuntuHelp:Beginners/BashScripting|suomi| [[::Beginners/BashScripting/fi|suomi]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/fr | • {{#if: UbuntuHelp:Beginners/BashScripting|français| [[::Beginners/BashScripting/fr|français]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/gu | • {{#if: UbuntuHelp:Beginners/BashScripting|ગુજરાતી| [[::Beginners/BashScripting/gu|ગુજરાતી]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/he | • {{#if: UbuntuHelp:Beginners/BashScripting|עברית| [[::Beginners/BashScripting/he|עברית]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/hu | • {{#if: UbuntuHelp:Beginners/BashScripting|magyar| [[::Beginners/BashScripting/hu|magyar]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/id | • {{#if: UbuntuHelp:Beginners/BashScripting|Bahasa Indonesia| [[::Beginners/BashScripting/id|Bahasa Indonesia]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/it | • {{#if: UbuntuHelp:Beginners/BashScripting|italiano| [[::Beginners/BashScripting/it|italiano]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/ja | • {{#if: UbuntuHelp:Beginners/BashScripting|日本語| [[::Beginners/BashScripting/ja|日本語]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/ko | • {{#if: UbuntuHelp:Beginners/BashScripting|한국어| [[::Beginners/BashScripting/ko|한국어]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/ksh | • {{#if: UbuntuHelp:Beginners/BashScripting|Ripoarisch| [[::Beginners/BashScripting/ksh|Ripoarisch]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/mr | • {{#if: UbuntuHelp:Beginners/BashScripting|मराठी| [[::Beginners/BashScripting/mr|मराठी]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/ms | • {{#if: UbuntuHelp:Beginners/BashScripting|Bahasa Melayu| [[::Beginners/BashScripting/ms|Bahasa Melayu]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/nl | • {{#if: UbuntuHelp:Beginners/BashScripting|Nederlands| [[::Beginners/BashScripting/nl|Nederlands]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/no | • {{#if: UbuntuHelp:Beginners/BashScripting|norsk| [[::Beginners/BashScripting/no|norsk]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/oc | • {{#if: UbuntuHelp:Beginners/BashScripting|occitan| [[::Beginners/BashScripting/oc|occitan]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/pl | • {{#if: UbuntuHelp:Beginners/BashScripting|polski| [[::Beginners/BashScripting/pl|polski]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/pt | • {{#if: UbuntuHelp:Beginners/BashScripting|português| [[::Beginners/BashScripting/pt|português]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/ro | • {{#if: UbuntuHelp:Beginners/BashScripting|română| [[::Beginners/BashScripting/ro|română]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/ru | • {{#if: UbuntuHelp:Beginners/BashScripting|русский| [[::Beginners/BashScripting/ru|русский]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/si | • {{#if: UbuntuHelp:Beginners/BashScripting|සිංහල| [[::Beginners/BashScripting/si|සිංහල]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/sq | • {{#if: UbuntuHelp:Beginners/BashScripting|shqip| [[::Beginners/BashScripting/sq|shqip]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/sr | • {{#if: UbuntuHelp:Beginners/BashScripting|српски / srpski| [[::Beginners/BashScripting/sr|српски / srpski]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/sv | • {{#if: UbuntuHelp:Beginners/BashScripting|svenska| [[::Beginners/BashScripting/sv|svenska]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/th | • {{#if: UbuntuHelp:Beginners/BashScripting|ไทย| [[::Beginners/BashScripting/th|ไทย]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/tr | • {{#if: UbuntuHelp:Beginners/BashScripting|Türkçe| [[::Beginners/BashScripting/tr|Türkçe]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/vi | • {{#if: UbuntuHelp:Beginners/BashScripting|Tiếng Việt| [[::Beginners/BashScripting/vi|Tiếng Việt]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/yue | • {{#if: UbuntuHelp:Beginners/BashScripting|粵語| [[::Beginners/BashScripting/yue|粵語]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/zh | • {{#if: UbuntuHelp:Beginners/BashScripting|中文| [[::Beginners/BashScripting/zh|中文]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/zh-hans | • {{#if: UbuntuHelp:Beginners/BashScripting|中文(简体)| [[::Beginners/BashScripting/zh-hans|中文(简体)]]}}|}} {{#ifexist: {{#if: UbuntuHelp:Beginners/BashScripting | UbuntuHelp:Beginners/BashScripting | {{#if: | :}}Beginners/BashScripting}}/zh-hant | • {{#if: UbuntuHelp:Beginners/BashScripting|中文(繁體)| [[::Beginners/BashScripting/zh-hant|中文(繁體)]]}}|}} |
{{#ifeq:UbuntuHelp:Beginners/BashScripting|:Beginners/BashScripting|请不要直接编辑翻译本页,本页将定期与来源同步。}} |
{{#ifexist: :Beginners/BashScripting/zh | | {{#ifexist: Beginners/BashScripting/zh | | {{#ifeq: {{#titleparts:Beginners/BashScripting|1|-1|}} | zh | | }} }} }} {{#ifeq: {{#titleparts:Beginners/BashScripting|1|-1|}} | zh | | }}
Bash scripting is one of the easiest types of scripting to learn, and is best compared to Windows Batch scripting. Bash is very flexible, and has many advanced features that you won't see in batch scripts. However if you are a 'non-computer-savvy' person that won't mean a thing to you. Basically Bash is the language that you will learn to love, much of everyday Ubuntu life is done/can be done at the Terminal. You will soon learn that most things can be done through both gui (Graphical User Interface (visual programs)) and cli (Command Line Interface), however some things are more easily achieved from one or the other. For example, changing file permissions of a folder and all its sub folders is more easily achieved from cli then gui.
Intro
In this document we will discuss useful everyday commands, as well as going a bit more in depth into scripting and semi-advanced features of Bash. Bash is not only used to run programs and applications, but it can also be used to write programs or scripts.
Bash -- Everyday Ubuntu life
During your time as an Ubuntu'er you will use the terminal to perform tasks such as
- Creating folders
- Deleting files
- Deleting folders and their sub-folders
- Opening applications as root
- Backing up your files
- Backing up your folders
- Checking system performance
- Check Devices
- Checking wireless connection
And many other things, the list above will be the commands we will discuss.
Commands
Creating folders
Creating folders can be done simply in the file manager nautilus by right clicking and selecting 'Create Folder', but if you want to do this from a cli environment you would type the following in the terminal:
sudo mkdir /home/joe/Desktop/new_folder
the mkdir (make directory) command creates the folder then the file path tells it where to create the folder. (I use sudo because if you try to create a folder anywhere other then /home or one of its sub-directories you will need root/superuser privileges. This goes for all commands in this section.)
Deleting files
Deleting files can be done like this
sudo rm /home/joe/file_to_be_deleted
the rm (remove) command is used to remove anything through a cli environment.
Deleting folders and their sub-folders
The command you are about to read can potentially (if used incorrectly) destroy your system!
sudo rm -rf /home/joe/useless_Parent_folder
This command is slightly different to the one before, it uses two options '-r' which means recursive (will delete the folder and all sub-folders) and '-f' means force (will not ask for your permission). This command is perfectly fine for deleting a dir and all its sub-dirs. The next commands should !!**!!NEVER!!**!! be run. Unless you want to say goodbye to your system.
sudo rm -rf /* sudo rm -rf /
This will delete everything from your root folder downwards, which if you did a standard install would be everything.
Opening applications as root
Sometimes you will want to edit a config file in your root folder, in order to save changes to this file you need root privileges so we need to open our text editor as root. (assuming your text editor is gedit)
gksudo gedit /path/to/conf_file.txt
gksudo is the same as sudo only it brings a box up to ask for your password, gksudo should always be used to open graphical applications as root. Serious damage can be done to your system by editing these files. It is advised to create a backup of any file you edit.
Backing up your files
To create a backup of a file, we're going to use the cp (copy) command. The basic syntax for cp is as follows:
cp source_file dest_file
This will copy the 'source_file' to the 'dest_file'. Now, using the previous example, we want to backup '/path/to/conf_file.txt'. To accomplish this, we type the following:
sudo cp /path/to/conf_file.txt /path/to/conf_file.txt.old
That's fine and dandy, but what if I want to copy my file to another directory? Well that's just as easy. Let's say instead of copying /path/to/conf_file.txt to the /path/to/ directory, you want to copy it to a directory where you store all of your backup files, say /my/backup/folder/. In order to accomplish this you would type:
sudo cp /path/to/conf_file.txt /my/backup/folder/ #saves conf_file.txt to /my/backup/folder/ #OR sudo cp /path/to/conf_file.txt /my/backup/folder/conf_file_new_name.txt
- This is a typical safety measure that has saved many users in the past from a complete disaster.***
Okay, so we know how to copy a file a) to a different filename and b) to a different folder. But how do we copy entire directories?
Backing up your directories
To backup one directory to another, we introduce cps '-r' (recursive) option. The basic syntax is as follow:
cp -r /directory/to/be/copied/ /where/to/copy/to/
So if we wanted to copy all of the contents of our /path/to/ folder to our /my/backup/folder, we would type the following:
sudo cp -r /path/to/ /my/backup/folder/foldername #foldername can be whatever you want the foldername to be
Checking system performance
If your computer starts to lag, you can see which applications are using the most CPU power with this command:
top
This is generally the same information given as the GUI application 'System Monitor'.
Check Devices
USB Devices If a USB device stops working, you may want to see if it is still connected/detected. To check if a device is connected/detected, type the following:
lsusb
PCI Devices PCI devices are checked with:
lspci
Checking wireless connection
To check the status on your wireless connection, use:
iwconfig
This also shows packets sent/received.
Scripting
Bash is primarily a scripting language, so it would be a crime not to talk about scripting. Let's dive straight in with a bash script. More precisely the infamous "Hello World" script. You can create a bash script by opening your favorite text-editor to edit your script and then saving it (typically the .sh file extension is used for your reference, but is not necessary. In our examples, we will be using the .sh extension).
#!/bin/bash echo "Hello, World"
The first line of the script just defines which interpreter to use. NOTE: There is no leading whitespace before #!/bin/bash. That's it, simple as that. To run a bash script you first have to have the correct file permissions. We do this with chmod (change mode) as follows:
sudo chmod 700 /where/i/saved/it/hello_world.sh #Gives read,write,execute permissions to the Owner # OR sudo chmod a+x /where/i/saved/it/hello_world.sh #Gives everyone execute permissions
This will give the file the appropriate permissions so that it can be executed. Now open a terminal and run the script like this:
/where/i/saved/it/hello_world.sh
Hopefully you should have seen it print Hello, World onto your screen. If so well done! That is your first Bash script. TIP If you type:
pwd
You will see the directory that you are currently working in (pwd stands for 'print working directory'). If your current working directory is /where/i/saved/it/, then you can shorten the above command to:
prompt$ pwd /where/i/saved/it prompt$ ./hello_world.sh
Now, lets get to more interesting aspects of Bash programming, Variables!
Variables
Variables store information basically. You set variables like this
var="FOO"
'var' can be anything you want as long as it doesn't begin with a number. "FOO" can be anything you want. To access the information from the variable you need to put a '$' in front of it like this:
var="FOO" echo $var
Try entering those lines into a terminal one at a time; you will see that the first one just gives you another prompt and the second one prints FOO. But that's all a bit boring. So let's make a script to ask the user for some information and then echo that information.
#!/bin/bash clear echo "Please enter your name" read name echo "Please enter your age" read age echo "Please enter your sex. Male/Female" read sex echo "So you're a $age year old $sex called $name"
read allows the user to input information where it is then stored in the variable defined after the read. read variable would take whatever input the user entered and store it in $variable. We then access this with echo and set up a neat sentence. This script is reasonably messy though; read has another function that could halve the size of this script.
#! /bin/bash clear read -p "Please enter your name : " name read -p "Please enter your age : " age read -p "Please enter your sex. Male/Female : " sex echo "So you're a $age year old $sex called $name"
That is more efficient code. However it's still a bit messy when run. A solution? Good old white spaces!
#! /bin/bash clear read -p "Please enter your name : " name echo "" read -p "Please enter your age : " age echo "" read -p "Please enter your sex. Male/Female : " sex echo "" echo "So you're a $age year old $sex called $name"
Now we have an efficient and clean Bash script.
If Statements
An if statement can be used to check for something and do something else depending on the outcome of the check. For example, if I had an 'apple', I would want to make sure it's still an 'apple' and not an 'orange' because I don't like Oranges! The syntax for an if statement is
if [something] then elif then elif then ....etc.... else fi
The elif is not necessary, but it can be used if needed. An if statement to check if our $fruit variable is an 'apple' would look like this
if [ $fruit = apple ] then echo "Good, I like Apples" else echo "Oh no, I hate Oranges!" fi
Just to explain this statement,
if [ the contents of $fruit is 'apple' ] then say "Good, I like Apples" if it's not, then say "Oh no, I hate Oranges!" finish
If statements are an easy concept to grasp as they are similar to the "if" used in spoken English. But say you wanted to have 4 or 5 checks, the answer may be to write 4 or 5 statements but that's not the most practical way. This is where elif comes in handy.
if [ $fruit = apple ] then echo "Good, I like Apples" elif [ $fruit = pear ] then echo "Good, I like Pears" elif [ $fruit = banana ] then echo "Good, I like Bananas" else echo "Oh no, I hate Oranges!" fi
This saves us from from repetitive scripting. There are better ways to check what the fruit is, but we won't go into that now.
Storing application stdout to a variable:
Application stdout ( what you see on the terminal screen, with an un-piped application ) can be saved and used in Bash. The simplest and most elegant way is to use the back-tick (`) this is not an apostrophe or quote (' or ") and is found on the same key as the tilde (~)
Example
#!/bin/bash fooVar=`who` echo $fooVar
This code should output the current users, their respective ttys, and date of login. Note that this strips newlines. Be sure to do any parsing in line ( | grep, etc ) and then pass it to a variable. We will try this again, but grep for tty7, the GUI's tty.
Example 2
fooVar=`who | grep tty7` echo $fooVar
This should output the single user that is currently logged into the WM. Let's move on to more advanced data manipulation within back ticks.
FUNctions
Bash lets you create a function on the fly, really handy if you plan on using a code block more then once. Functions reduce the amounts of editing you have to do in a script, if and when you have to update your script. Let's get to it!
Example
Here is an example script:
#!/bin/bash echo "echo is Called" echo "Functions are FUN!" echo "echo is Called"
Although this example is simple, you can see that if you want to change "echo is Called" to say "foo is Called" you would have to edit twice. Below is the same app using functions.
#!/bin/bash echoFunction() { echo "echo is Called" } fooBar() { echo "Functions are FUN!" } echoFunction; fooBar; echoFunction; # You call functions without (), just the function name then a semicolon.
This example, as you can see may be longer now, but you can imagine how, adding features, this will eliminate code and reduce complexity. Also, you can see if you want to change the echo call, you have to edit one line, not two.
Debugging
I always find it useful to trace a script to find out why something does not work as expected. To trace, start it trough bash explicitly and use the -x option, like so:
bash -x ./script.sh
This will write each command to standard error (preceded by a ‘+ ’) before it is executed.
tr
tr is one of the most basic applications to pipe data through that uses a basic scripting syntax. In this case, it accepts Regular Expressions. Let's do a normally complicated task, transforming a string to all uppercase.
Example
#!/bin/bash read foo var=`echo $foo | tr "{a-z}" "{A-Z}"` # {a-z} Matches a through z # {A-Z} matches A through Z echo $var
The output should look something like this:
this is a test THIS IS A TEST
tr also can TRanslate strings, so let's translate all "tar" in $foo to "bar".
Example
#!/bin/bash read foo var=`echo $foo | tr "t" "b"`
the output should look something like this:
I love tars I love bars
awk
AWK ( Short for Aho, Weinberger & Kernighan ) awk has its own custom scripting language, suitable for a tutorial by itself, so I will cover only the basics to help assist when you are bash scripting. This is not meant to be complete or comprehensive in any way.
pidof clone
Let's make a quick pidof clone that prompts for a process identifier, then echoes the process ID.
#!/bin/bash read pname ps -ef | grep -v grep | grep $pname | awk '{print $2}'
Single quotes are used to pass the awk command(s). The curly braces are to use the awk language (for stuff like prints, ifs, etc.). Print prints the column passed given by the $ markup, space delimited. There are a lot more commands than the print command, including if statements, etc., and is worth looking into if you are interested in what you see here!
sed
sed is one of the most complicated scripting languages on the GNU / Linux system. I am only going to cover the s/ command here.
Basic Substitution
Try this out to show that sed can not only replace inline, but unlike tr, replace with a longer or shorter string than before.
#!/bin/bash read foo echo $foo | sed "s/foo/bars/"
When this command is run, it should substitute the first appearance of "foo" with "bars". This is an example of the output.
I love to go to foo I love to go to bars