Bash scripts

From Teknologisk videncenter
Revision as of 11:44, 24 August 2009 by Heth (talk | contribs) (Oprettelse af scriptet)
Jump to: navigation, search

Denne artikel er en del af den samlede dokumentation af bash.

Mit første bash script

Hvor skal script-filen placeres

Det er vigtigt at scriptet ligger i et bibliotek der er med i søgning i variablen $PATH

[heth@mars ~]$ <input>who am i</input>
<notice>heth</notice>             ttyp2    Aug 24 07:51 (192.168.22.136)

[heth@mars ~]$ <input>echo $PATH</input>
/sbin:/bin:/usr/sbin:/usr/bin:<notice>/home/heth/bin</notice>

Biblioteket hvor brugeren heth skal ligge sin scripts hedder /home/heth/bin. Opret dette bibliotek hvis det ikke eksisterer og skift til dette bibliotek.

[heth@mars ~]$ <input>mkdir /home/heth/bin</input>
[heth@mars ~]$ <input>cd /home/heth/bin</input>

Oprettelse af scriptet

Før vi opretter scriptet er det nødvendigt at vide hvor bash er installeret på maskinen. Bash programmet skal alle andre programmer er normalt placeret i et bin eller sbin bibliotek. På min maskine er den installeret i /usr/bin/bash som vist nedenfor.

[heth@mars ~/bin]$ <input>whereis bash</input>
bash: <notice>/usr/bin/bash</notice> /usr/local/man/man1/bash.1.gz /usr/ports/shells/bash

Opret scriptet med din ynglingseditor. pico,nano,edit,emacs eller vi. vi editoren findes på alle versioner af Linux og Unix, og er derfor en god editor at kende. Den kan dog drille lidt, så vælg pico hvis du er i tvivl - og den er installeret på din Linux/Unix boks.

filen oprettes med

[heth@mars ~/bin]$ <input>vi script1</input>

Indtast nedenstående bash script

#!/usr/bin/bash

echo -en "Hvad er dit navn: "
read NAVN
echo -e "Dit navn er $NAVN"

Afvikling af shell scriptet

For at afvikle shell scriptet skal bash vide at det er en udførbar fil. Altså et program der kan blive til en process.

[heth@mars ~/bin]$ <input>ls -l script1</input>
<notice>-rw-r--r--</notice>  1 heth  heth  99 Aug 24 10:41 script1
[heth@mars ~/bin]$ <input>chmod +x script1</input>
[heth@mars ~/bin]$ <input>ls -l script1</input>
<notice>-rwxr-xr-x</notice>  1 heth  heth  99 Aug 24 10:41 script1

nu er scriptet klar til at køre

[heth@mars ~/bin]$ <input>script1</input>
Hvad er dit navn: <input>Mickey Mouse</input>
Dit navn er Mickey Mouse