Scripting 101

0 views

Published on

Short primer in Bash scripting

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
0
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Scripting 101

  1. 1. Scripting 101
  2. 2. My First Sony ^H^H^H hellscript#!/bin/bashecho “Hello World!”$ sh script.sh Hello World
  3. 3. Output redirectionThere are 3 file descriptors: Examples: stdin, stdout and stderr. 1. ls -l > ls-l.txtBasically you can: 2. grep da * 2> grep-errors.txt  redirect stdout to a file 3. grep da * 1>&2  redirect stderr to a file 4. grep * 2>&1  redirect stdout to a stderr 5. rm -f $(find / -name core) &> /dev/null  redirect stderr to a stdout  redirect stderr and stdout to a file  redirect stderr and stdout to stdout  redirect stderr and stdout to stderr1 represents stdout and 2 stderr.
  4. 4. PipesPipes can redirect output from one command to anotherExample:$ cat /etc/passwd | grep „whoami‟
  5. 5. VariablesSTR=“Hello World!”OF=“/var/my-backup-$(date +%Y%m%d).tgz”#!/bin/bashSTR=“Hello World!”echo $STR#!/bin/bashOF=“/var/my-backup-$(date +%Y%m%d).tgz”tar -cZf $OF /home/me/
  6. 6. Local variables#!/bin/bashHELLO=Hellofunction hello { local HELLO=World echo $HELLO}echo $HELLOhelloecho $HELLO
  7. 7. Conditionsif [expression]; Examples:then code if expression is true. #!/bin/bash if [ "foo" = "foo" ]; thenfi echo “expression evaluated as true” fi #!/bin/bashif … then T1="foo"else T2="bar" if [ "$T1" = "$T2" ]; thenelseif echo “expression evaluated as true” else echo “expression evaluated as false” fi
  8. 8. Loops3 kinds of loops Examples: #!/bin/bash for loop for i in `seq 1 10`; do echo $i while loop Done until loop #!/bin/bash COUNTER=0 while [ $COUNTER -lt 10 ]; do echo “The counter is “ $COUNTER let COUNTER=COUNTER+1 done
  9. 9. Assignment:Write a linux shell script to automagicallycreate 1000 user accounts. Make sure theirdefault password is “Hello123”(hint: you cannot set the pasword with the –poption….)
  10. 10. Useful files and commandsnano, joe, vi (editors)/etc/passwduseraddpasswdrm -rf

×