Part5bash - Done

18
Bagian 5: BASH

description

deva

Transcript of Part5bash - Done

Bagian 5: BASH

Hari 1 Bagian 1:Pengenalan Sistem Operasi LinuxBagian2: Lingkungan ber-graphis 01:30Bagian 3: Perintah Dasar Bagian4: Filesystem Linux 02:00

Hari 2 Bagian5: Bash 02:30Bagian6: Editor Text vi/vim 00:30Bagian7: Mengatur Users, Groups, dan Permissions 03:00

Hari 3 Bagian8: Processes 02:30Bagian9: Perintah Dasar Networking 00:30Bagian10: Redirection & Pipes 03:00

Hari 4 Bagian11: String ProcessingBagian12: Tool Dasar Administrasi Sistem 02:30

TujuanSetelah menyelesaikan bagian ini, diharapkan anda bisa dan mengerti tentang:command-line shortcutscommand-line expansionhistorydan tricks pengeditangnome-terminal1. Get to Know the Command Shells2. Execute Commands at the Command Line3. Get to Know Common Command Line Tasks4. Understand Command Syntax and Special Characters5. Use Piping and Redirection

Pengantar ShellShell akan bertugas sebagai jembatan antara user dan linuxAdalah sebuahcommand interpreter,yang akan menerima apapun yang kita ketik dicommand-line dan meneruskannya ke linuxBerjalan lebih cepat dari GUIStandard Linux shell adalahbashbash = Born Again SHellMerupakan shell generasi penerus dari Stephen Bourne AT&T's versi asli Unix shShell will serves as an interface between user an operating systemIt is actually a command interpreter, it accepts a users entries, interpret them, convert them to system calls, and delivers system messages back to the user in other words a shell is a command interpreter that takes what you type in at the command-line interface and passes it to the linux operating system.

Commands that you run in the shell allow you to do more than any GUI tool available on a Linux operating system.

Commands that you type in at the shell execute faster than the GUI.

Pengantar ShellBerikut contoh-contoh shell terkenal:The Bourne shell/bin/sh;Di RHEL/CentOS: symbolic link to /bin/bashThe Bourne Again shell (/bin/bash)The Korn shell (/bin/ksh)The C shell/bin/csh;Di CentOS: symbolic link to /bin/tcshThe TC shell (/bin/tcsh)The various shells differ in the functionality they provideEvery shell can be started like a program and you can switch at any time to a different shell.For example, you can switch to the C shell by entering tcsh; you can switch to the Korn shell by entering ksh.Unlike most other programs, the shell does not terminate on its own.You need to enter the command exit to return to the previous shell.The standard Linux shell is bash, so we will only cover bash shell in this objective.

Online manual is available for each installed shell:

http://www.gnu.org/software/bashBASH Web site with online manual, FAQ, and current releases

http://www.gnu.org/software/bash/manual/bash.htmlBASH online manual

http://www.zsh.orgZ shell Web site with referrals to FAQs and current downloads.

http://www.tcsh.orgTCSH Web site with detailed support including manual, tips, FAQ, and recent releases

http://www.kornshell.comKorn shell site with manual, FAQ, and references

Pengantar ShellSebuah shell dimulai di console text segera setelah user loginKita sebut ini login shellShell yang mana yang akan dipakai user ditentukan di database(/etc/passwd).You can switch between shell, you can switch to the C shell by entering tcsh; you can switch to the Korn shell by entering ksh.

Unlike most other programs, the shell does not terminate on its own. You need to enter the command exit to return to the previous shell.

A shell is started at a text console right after a user logs in. This is called the login shell.

Which shell is started for which user is determined in the user database.

bashShellbash shell adalah default shell di RHEL/CentOS, ditandai dengan prompt tanda dolar ($)Kalau user root, prompt nya beda, yaitu tanda #. prompt shell ini menandai dimulainya command line alias baris perintahAnda bisa memasukan perintah bersama opsi-opsi dan argumen-argumen di prompt tsbContoh:$ ls -l$ ls -l mydataFor example, an -l option, the ls command display a line of information about each file, listing such data as its size and the date and time it was last modified. Linux uses it to distinguish an option from an argument.$ ls -lIf you wanted only the information displayed for a particular file, you could add that files name as the argument, following the -l option:$ ls -l mydata-rw-r--r-- 1 christo weather 207 Feb 20 11:55 mydata

login ShellSetiap kali user login ke system, shell akan langsung otomatis berjalanShell bisa juga dijalankan di shell yg sedang jalan, namanya non-login shellPerbedaanya cuma di file konfigurasi yang dibaca oleh system saat shell dijalankanShell juga jalan otomatis ketika user login via X display managerbash Configuration FilesTo customize bash for an interactive session, you need to know about the configuration files and about the order in which they areprocessed.

To understand how shells work, you need to know the difference between the following:Login ShellsNon-Login Shells

Login ShellsA login shell is started whenever a user logs in to the system.

By contrast, any shell started from within a running shell is a non-login shell.

The only differences between these two are the configuration files read when starting the shell.

A login shell is also started whenever a user logs in through an X display manager. Therefore, all subsequent terminal emulation programs run non-login shells

Pattern Matching* any sequence of characters? any one character[abc] the specified range[0-9] matches a range of numbers[abc] matches any of the character in the list[^abc] matches all except the characters in the listSquare brackets are most commonly used with asterisks to match strings starting with a specific range.Shell pattern matching

The shell pattern matching facilities provide a short-hand for specifying filenames and matching strings.

AsteriskThe asterisk matches any string of characters including the empty string. a* will match any string starting with an "a including the string "a" itself.

Question MarkThe question mark matches any one missing character. a? will match any string starting with an "a and followed by exactly one character.

Square bracketsSquare brackets indicate sets of characters and will match a single character which is in the set. Two characters separated by a dashmatch any character lexigraphically between the pair. More than one range can be used within the square brackets.[abc] will match any of a b c[a-c] will match any of a b c[a-cA-c] will match any of a b c A B C

shortcutTombol Tab auto completionhistory list dari commands yg terakhir jalanTanda tilde (~) merujuk ke home direktori userThe Tab Key Press TAB key #xclo #xclock

History run history command #history

The tilde - ~

#cat ~/.ssh/known_hosts

quotingQuoting - protect characters with special meaning to shell\ shields one character'...' shields all enclosed characters ( except ')"..." shields enclosed characters except for $ ` " \Example:#date=20090320#echo $date20090320#echo \$date$date# echo '$date'$dateQuotingQuoting is used to shield the shell's special characters ( often referred to as metacharacters ) from interpretation.BackslashThe backslash will shield any single character it precedes.Single forward quoteAll characters enclosed between a pair of single forward quotes are shielded - apart from the character itself !Double quotesAll the characters enclosed between a pair of double quotes are shielded except for $ ` \ and Another example:$ touch answers?$ ls answers\?answers?Placing the filename in double quotes will also quote the character.$ ls "answers?"answers?In this case, the user quotes the ? with a preceding backslash to reference the filename. Originally, the ? is, a file expansion character and would match any filename beginning with answers that has one or more charactersAnother Example:A double quote may be quoted within double quotes by preceding it with a backslash.[christo@samba1 ~]$ echo "$date"20090320[christo@samba1 ~]$ echo "`date`"Sun Apr 20 11:22:06 CEST 2003[christo@samba1 ~]$ echo "I'd say: \"Go for it!\""I'd say: "Go for it!"[christo@samba1 ~]$ echo "\"More input>"[christo@samba1 ~]$ echo "\\"\

redirectionPipes |Output redirection>>>Input redirection wholist

will create or overwrite a file which contains a list of who is on the system.The >> character appends the output of the command into the named file.

bash$ who >> wholist

will append a list of who is on the system to the end of the file wholistInput redirection

The < character takes its input from the named file.mail christo < /etc/motdwill send the message of the day ( /etc/motd ) by email to user christo.

Here DocumentsThe text between the delimiters is used as the standard input of the command.Between the delimiters shell variable expansion and command substitution are performed.cat `command`echo Todays date is `date`Todays date is Wed Jan 18 16:30:28 GMT 1995Brace Expansion, dg tanda {}:{}jalan cepat untuk menampilka strings yg berulang(repetitive strings)$ echo file{1,3,5}file1 file3 file5$ rm -f file{1,3,5}Command substitutionCommands enclosed by backquotes are run by the shell and the text enclosed by and including the backquotes are replaced by the result of the command. Newlines in the output from the command are replaced by spaces.The shellCommand substitution is good for presenting arguments to commands or for assigning shell variables, egbash$ Date=`date`bash$ echo $DateThu Jun 8 12:00:28 BST 1995The shell actually evaluates the commands between the backquotes by executing a new shell and so any shell constructs can be used within the backquotes.bash$ Numusers=`who | wc -l`bash$ echo $Numusers250

ScriptFile text biasa yang berisi perintah-perintah shellFile tsb harus ber-attribut executable dan readableTidak perlu dikompilasi dan diinterpretasiBahasa C, yang di kompilasi akan berjalan lebih cepat dari shell scriptTapi script lebih mudah ditulisDan biasanya menggunakan perintah Unix yang lain untuk menyelesaikan tugas2nyaBerguna untuk:Automating tasksTroubleshooting and sysadminSimple applicationsManipulation of text or files-Shell ScriptA shell script is just a normal Unix file which contains Unix and shell commands. The simplest shell scripts simply group together commonly used sequences of commands. More complex use the shell's programming syntax to perform more advanced tasks. Not compiled but interpreted. This means that each time they are run a shell is executed to read the file and run the commands it contains. Languages which are compiled, such as C, will produce a compiled code which will run faster than an equivalent shell script. Since shell scripts usually use other Unix commands to achieve their task, and are much easier to write, this usually does notmatter.

Execute BitLike any program under Unix a shell script must have the execute permission bit turned on.To do this usebash$ chmod +x script-name

In fact since the shell actually reads the script each time it is executed you need to turn the read permission bit on as well. In general when you create a file under Unix you are given read and write permission on the file, so you need only add execute permission.

Script cont#adalah tanda comment#! tandamagic sequence - yg menyebutkan command interpreter#!/bin/shecho "Hello world"Comment CharacterThe comment character in the shell is the # Any text between the # character and a newline is ignored by the shell.

A comment character will only be recognised as the first character in a file or following a space, tab or newline. The comment character can of course be quoted to escape its meaning. As with all programming languages it is very important to comment your code!Command Interpreter

The special directive #! as the first two characters of a file tell Unix that the rest of the line identifies the program which should be used to run this file.

So to make sure a script runs under the Bourne shell use#!/bin/sh

Note that this special directive is only recognized if it is the first two characters in the file and so there should be no spaces before the #. There can however be spaces between the ! and the name of the interpreter.

Practical instructionsWrite a shell script, called count-users, which counts how many users are on the system.( Tip - who command shows all the users on the system - one per line. The wc -l command prints how many lines it had as input ).

Script contStep 1:Gunakanviuntuk membuat file text yang berisi perintah-perintah aliascommandsStep 2: Jadikan diaexecutable:chmod u+x script1.shStep 3: jalankan seperti demikian:./script1.shAtau letakan script tsb di folder executable (misal/usr/bin) atau sebutkan jejak lengkap aliasabsolute pathdi consoleComment CharacterThe comment character in the shell is the # Any text between the # character and a newline is ignored by the shell.

A comment character will only be recognised as the first character in a file or following a space, tab or newline. The comment character can of course be quoted to escape its meaning. As with all programming languages it is very important to comment your code!Command Interpreter

The special directive #! as the first two characters of a file tell Unix that the rest of the line identifies the program which should be used to run this file.

So to make sure a script runs under the Bourne shell use#!/bin/sh

Note that this special directive is only recognized if it is the first two characters in the file and so there should be no spaces before the #. There can however be spaces between the ! and the name of the interpreter.

Practical instructionsWrite a shell script, called count-users, which counts how many users are on the system.( Tip - who command shows all the users on the system - one per line. The wc -l command prints how many lines it had as input ).

VariableSetVariable=valueDe-reference$VariableVariable NamesMust start with an alphabeticMay contain a-zA-Z0-9_Are case sensitive$FOO,$Foo and $foo are differentShell VariablesUsing shell variables should already be a familiar operation, eg setting your terminal type is done by setting the TERM shell variable.

A shell variable is simply set by equating it to a value. Note that there should be no spaces either side of the = and if the variable's value contains spaces or tabs it should be quoted.

bash$ Greeting="Hullo Tony"

A variable's value is obtained by prefixing it with the $ character

bash$ echo Greeting Greeting bash$ echo $Greeting HulloTony

Variable NamesVariables names may comprise upper and lower case alphabetic characters, digits and underscores. A user defined variable namecannot start with a digit. As with most things in Unix variable names are case sensitive, eg FOO and foo are two distinct variables.Of course the variable's value can be any string of characters.

Special shell variablesSome variables have special significance to the shell. For example, the PATH variable is used by the shell to contain the list ofdirectories to search for commands. Other variables have special meaning to other Unix utilities, for example the TERM variable contains the current terminal type.

Akhir Bagian 5Questions and AnswersSummary