#!/bin/bash clear echo "The script starts now" echo "Hi, $USER!" echo echo "Iwill now fetch you a list of connected users:" echo w echo echo "I'm setting two variables now." COLOUR="black" VALUE="9" echo "This is a string : $COLOUR" echo "And tis is a number : $VALUE" echo echo "I'm giving you back your prompt now." echo |
set -x w set +x |
short notation |
long notation |
result |
set -f |
set -o noglob |
*を使用時のファイル名生成をできなくする |
set -v |
set -o verbose |
shell input lines をprint |
set -x |
set -o xtrace |
実行前にcommands trace をprint |
full_name="Franky M.Singh" bash echo $full_name -->なし exit export full_name bash echo $full_name --> Franky M.Singh export full_name="Charles the Great" echo $full_name --> Charles the Great exit echo $full_name --> Frankey M.Singh parentでFranky--をexportして subshell(Frankyをexpoted)の変数値を変える parentの変数値は不変 |
#!/bin/bash # positional.sh # This script reads 3 positional parameters and prints them out POSPAR1="$1" POSPAR2="$2" POSPAR3="$3" echo "$1 is the first positional parameter ,\$1." echo "$2 is the second positional parameter ,\$2." echo "$3 is the third positional parameter ,\$3." echo echo "The total number of positional parameters is $#." positional.sh one two three four five |
grep dictionary /usr/share/dict/words dictionary echo $_ /usr/share /dict/words |
mozilla & [1] 11064 echo $! 11064 (bg) |
echo $? --> 0 (exit code =0) ls doesnotexist -=> ls:doesnotexist:No such file echo $? --> 1 (error code) |
#!/bin/bash |
#!/bin/bash |
date=20021226 echo $date --> 20021226 echo \$date --> $date |
echo "$date" --> 20021226 echo "`date`" --> SunApr20 11:12:22 echo "I'd say \"Go for it!\"" --> I'd say "Go for it!" echo "\" More input> echo "\\" --> \ |
example echo $FRANKY --> no output echo ${FRANKY:=Franky} --> Franky (しかしspecial parameter 特にpositional parameterはこの方法では割り当てできない。) |
# 第1引数を echo する関数 |
set -o noclobber (redirection命令でファイル上書きさせない). touch test date > test :cannot overwrite existing file set +o noclobber date > test |
-u(unset variablesをエラーとみなす) echo $VAR --- 表示なし set -u echo $VAR --> unbound variable set +u |
set -o noglob (special character をexpand されないようにする) touch * ls -l * --rw-rw---| -- * |
command |
result |
a\ c\ d i\ p r s w |
append text below current line change text in the current line with new text delete text insert text above current line print text read s file search and replace write to afile |
option |
effect |
-e script |
script中にコマンドセットを入れて走らせる |
-f |
SCRIPT-FILEファイル中に含まれるコマンドを付加し走らせる。 |
-n |
silent mode |
-V |
print version information and exit |
example 1 This ia the first line of an example text 2 It is a text with erors 3 Lots os erors 4 So much erors, all these eros are making me sick. 5 This is a line not containing any errors 6 This is the last line. |
cat script.sed 1i\ <html>\ <head><title> Sed generated html </title></head>\ <body bgcolor=#fffffff">\ <pre> $a\ </pre>\ </body>\ </html> |
cat text2html.sh #!/bin/bash # # # echo "converting $1..." SCRIPT="/home/ouryouji/scripts/script.sed" NAME=$1 TEMPFILE="/var/tmp/sed.$PID.tmp" sed "s/\n/^M/" $1 | sed -f $SCRIPT | sed "s/^M/\n/" > $TEMPFILE mv$TEMPFILE $NAME echo done |
cat test line 1 line 2 line 3 |
awk '/\<[a|x].*\.conf$/ { print $9 } END { print \
"Can I do anything else for you, mistress?" }'
cat diskrep.awk BEGIN {print "***WARNING ASRNING WARNING***"} /\<[[8|9][0-9]%/ {print "Partition" $6 "\t: " $5 "full!"} END {print "***Give money for new disks URGENTLY***"} df -h | awk -f diskrep.awkと実行 |
cat testawk record1 data1 record2 data2 |
cat processed.awk BEGIN {OFS="-"; ORS="\n--->done\n"} {print "record number" NR ":\t" $1,$2} END {print "Number of record processed: "NR} |
cat revenues 20021009 20021013 consultancy BigComp 2500 20021015 20021020 training EduComp 2000 20021112 20011123 appdev SmartComp 1000 20021204 20021215 training EduComp 5000 |
cat total.awk {total=total+$5} {print "Send bill for " $5 "dollar to $4" End {print"-----------\nTotal revenue: " total} |
cat make-html-from-text.awk BEGIN{print "<html>\n<head><title>Awk-generated HTML\ </title></head>\n<body bgcolor=\"#ffffff\">\n<pre>"} {print $0} END {print "</pre>\n</body>\</html>\"} |
[-a FILE] |
true if FILE exists |
[-b FILE] |
true if FILE exists and is a block-special file |
[-c FILE] |
true if FILE exists and is a character-special file |
[-d FILE] |
true if file exists and is a directory |
[-e FILE] |
true if FILE exists |
[-f FILE] |
true if FIL Eexists and is a regular file |
[-g FILE] |
true if FILE exists and its SGID bit is set |
[-h FILE] |
true if FILE exists and is a symbolic link |
[-k FILE] |
true if FILE exists and its sticky bit is set |
[-p FILE] |
true if FILE exists and is a named pipe(FIFO) |
[-r FILE] |
true if......and is readable |
[-s FILE] |
true if.......and has a size grater than 0 |
[-t FD] |
|
[-u FILE] |
true if ......and its SUID(set user ID) bit is set |
[-w FILE] |
true if .......and is writable |
[-x FILE] |
true if .......and is executable |
[-O FILE] |
true if .......and is owned by the effective user ID |
[-G FILE] |
true if ........ ..............................effective group ID |
[-L FILE] |
true if.........and is a symbolic linc |
[-N FILE] |
true if .........and has been modified since it was last read |
[-S FILE] |
true if .........and is a socket |
[FILE1 -nt FILE2] |
|
[FILE1 -ot FILE2] |
|
[FILE1 -ef FILE2] |
|
[-o OPTIONNAME] |
true if shell option "OPTIONNAME" is enabled |
[-z STRING] |
true if the length of "STRING" is zero |
[-n STRING] or [STRING] |
true if the length of "STRING" is non-zero |
[STRING1==STRING2] |
|
[STRING1!=STRING2] |
|
[STRING1<STRING2] |
|
[STRING1>STRING2] |
|
[Arg1 OP Arg2] |
OPは-eq,-ne,-lt,-le,-gt,geの一つArg1,2ともinteger. |
Operation |
Effect |
[!EXPR] |
true if EXPR is false |
[(EXPR)] |
EXPRの値を返す。opratorの通常の手続きに重ねうる。 |
[EXPR1 -a EXPR2] |
both EXPR1 AND EXPR2 are trueの時真 |
[EXPR1 -o EXPR2] |
either EXPR1 OR EXPR2 is true の時真 |
#!/bin/bash echo "This script checks the existance of the message file" echo "checking..." if [-f /var/usr/log/messages] then echo "/var/log/message exists." fi echo echo "done" |
if [-o noclobber] then echo "Your files are protected against accidental overwriting using redirection" fi |
if [$? -eq 0] then echo 'That was a good job' fi |
test commandはany unix command でも可 if ! grep $USER /etc/passwd then echo "Your user account is not managed locally"; fi echo $? 0 |
grep $USER /etc/passwd if [$? -ne 0]; then echo "not a local account" ;fi |
num=`wc -l work.txt` echo $num => 201 if [$num -gt 150] then echo ; echo "You've worked hard enough for today" echo; fii |
cronで毎日曜日に実行されるプログラム #!/bin/bash #dateコマンドで週の数を計算 WEEKOFFSET=$[$(date +%V")%2] #余りがなければ偶数週 #メッセージ if [$WEEKOFFSET -eq "0"]; then echo "日曜夜ゴミ箱を開けよ" | mail -s "Garbage cans out" |
if ["$(whoami)]"!='root'; then echo "You have no permission to run $0 as non-root user." ; exit 1; fi |
[ "$(whoami)" != 'root' ] && ( echo you are using a non-privileged account; exit 1 )
test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)
gender="female" if [[ "$gender"== f* ]] rhen echo "Pleasure to meet you, Madame."; fi (regular expression も) |
gender=="male" if [[ "$gender"== f* ]] then echo "pleasure to meet you,Madam." else echo "How comr the lady hasn't got a drink yet?" fi [[ は変数値のsplitting とpathname expansionを抑える。 |
su - # if ! grep ^$user /etc/passward 1> /dev/null then echo "your user account is not managed locally else echo "your account is managed from the local /etc/password file" fi |
cat penguin.sh #!/bin/bash #This script lets you present different menus to Tux, He'll only be happy when given a fish if [ "$1" == fish ]; then echo "HMMMM fish... Tux happy!" else echo "Tux don't like that .Tux wants fish!" fi penguin.sh apple etc |
cat weight.sh #!/bin/bash # This script prints a message about your weight weight="$1" height="$2" idealweight= $[ $height - 110] if [ $weight -lt $idealweight ]; then echo " you should eat a bit more fat" else echo "You should eat a bit more fruit" fi bash -x weight.sh 55 169 |
cat weight.sh #!/bin/bash # This script prints a mesage about your weight if you give it your # weight in kilos and height in centimeters if [ ! $# == 2 ]; then echo "Usage: $0 weight_in_kilos length_in_centimeters" exit fi weight="$1" height = "$2" 以下仝 引数が2以外ならエラー |
#!/bin/bash |
例(crontabに入れて毎日実行できる) /etc/cron.daily> cat disktest.sh #!/bin/bash # This script does a very simple test for checking disk space space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 | cut -d "%" -f 1 -` altervalue=80 if ["$space" -ge "$altervalue"] ; then echo "At last one of my disks is nealy full! | mail -s "daily disk check" root else echo "disk space normal "| mail -s "daily diskcheck" root fi |
#!/bin/bash # This script will test if we're in the leap year or not year=`date +%Y` if [$[$year %400] -eq "0"]; then echo "This is a leap year . February has 29 days." elf [$[$year %4] -eq "0"; then if [$[$year %100] -ne 0]; then echo "This is a leap year , February has 29 days." else echo "This is not a leap year , February has 28 days." fi else echo "This is not a leap year, February has 28 days." fi |
year=`date +%Y` if (( ("$year" %400) == "0" )) || (( ("$year" %4 =="0") && ("$year %100 !="0") )) echo "This is a leap year... else echo "This is not a leap year." fi |
#!/bin/bash # This script lets you present different menus to Tux. He # will only be happy when givena fish. We've also added a # dorphin and (prsumably) a camel. if ["$menu"=="fish" ] ;then if ["$animal"=="penguin"] ; then echo "Humm fish... Tux happy!" elif ["$animal"=="dolphin"]; then echo "Pweetpeet...!" else echo "*prrrr t*" fi else if [ "$animal" =="penguin" ;then echo "Tux does'nt like that. Tux wants fish!" exit 1 elif [ "$animal"=="dolphin"] ; then echo "Pweepwish........... " exit 2 else echo"Will you read this sign?!" exit 3 fi fi このスクリプトはfeed.shから呼ばれる. |
#!/bin/bash # This script acts upon the exit status given by pehguin.sh export menu="$1" export animal="$2" feed="/home/ouryouji/scripts/penguin.sh" $feed $menu $animal case $? in 1) echo "guard:You'd better give'n a fish, less they get violent" ;; 2) echo "Guard : It's because of people like you that they are leaving earth all the time." ;; 3) echo "Guard: By the food that the zoo provide for the animals, you***,how do you think we survive?" ;; *) echo "Guard; Don't forget the guide!" ;; esac |
#!/bin/bash # This script does a very simple test for checking disk space space=`df -h | awk '{print $5}' | grep %| grep -v Use | sort -n | tail -1 | cut -d"%" -f1 -` case $space in [1-6]*) Message="All is quiet." ;; [7-8]*) Message="Start thinking cleaning out some stuff" ;; 9[1-8]* Message="Better hurry with that new disk... ;; 99) Message="I'm drawning here!" ;; *) Message="I seem to be running with an unexixtent amount of disk space .." ;; esac echo $Message | mail -s "dik report `date`" ouryouji You have new mail が実行結果(/var/spool/mail/ouryouji) subject : disk report |
case "$1" in start) start ;; stop) stop ;; status) status anacron ;; restart) stop start ;; condrestart) if test "x`pidof anacron`" | =x; then stop start fi ;; *) echo $"Usage : $0{start | stop | restart | condrestart | status}" exit esac |
#!/bin/bash |
Option | Meaning |
---|---|
-a ANAME | wordsはindexゼロで始まる配列変数ANAMEに割り当てられる.array=( |
-d DELIM | 入力の区切りをnewlineではなくdelimitatorとする。 |
-e | readline is used to obtain the line. |
-n NCHARS | n characters をよむ。 |
-p PROMPT | プロンプトを表示し端末から入力 |
-r | \をエスケープとして使わない. |
-s | Silent mode. |
-t TIMEOUT | Cause read to time out and return failure if a complete line of input is not read within TIMEOUT seconds. This option has no effect if read is not reading input from the terminal or from a pipe. |
-u FD | Read input from file descriptor FD. |
#!/bin/bash # This script will test if you have given a leap year or not. echo "Type the year that you want to check(4digits), follwed by [ENTER]:" read year if (( ("$year" %400) == "0")) || (( ("$year" %4 =="0") && ("$year" %100 != "0") )); then echo "$year" is a leap year." else echo "This is not a leap year." fi leaptest.shで実行 |
#!/bin/bash # This is a program that keeps your address book up to date. friends=/var/tmp/ouryouji/friends echo "Hello, "$USER". This script will register you in ouryouji's friends database." echo -n "Enter your name and press [ENTER]:" read name echo "Enter your gender and press [ENTER]:" read -n 1 gender echo grep -i "$name" "$friends" if ["$?" == 0] ; then echo "You are already registered, quitting." exit 1 elif ["$gen der" =="m"] ; then echo "You are added to ouryouji's friends list." exit 1 else echo -n "How old are you?" read age if ["$age -lt 25 ] ;then echo -n "Which colour of hair do you have?" read colour echo "$name $age $colour" >> "$friends" echo "You are added to ouryouji's friends list" exit 1 fi fi cp friends.sh /var/tmp; cd /var/tmp touch friends ; chmod a+w friends |
上記fdが実際のデバイスをどう指すか
michel ~> ls -l /dev/std*
lrwxrwxrwx 1 root root 17 Oct 2 07:46 /dev/stderr -> ../proc/self/fd/2
lrwxrwxrwx 1 root root 17 Oct 2 07:46 /dev/stdin -> ../proc/self/fd/0
lrwxrwxrwx 1 root root 17 Oct 2 07:46 /dev/stdout -> ../proc/self/fd/1
michel ~> ls -l /proc/self/fd/[0-2]
lrwx------ 1 michel michel 64 Jan 23 12:11 /proc/self/fd/0 -> /dev/pts/6
lrwx------ 1 michel michel 64 Jan 23 12:11 /proc/self/fd/1 -> /dev/pts/6
lrwx------ 1 michel michel 64 Jan 23 12:11 /proc/self/fd/2 -> /dev/pts/6
at .. at > ls -l /proc/self/fd/ > /var/tmp/fdtest.at at > <EOT> (Ctrl+Dのこと) cat /var/tmp/fdtest.at lr-x..... 0 -> /var/spool/cron/at jobs (入力) 1 /var/tmp/fdtest.at (出力) 2 /var/ (エラー) 3 |
exec 4> result.txt filter body.txt | cat header.txt /dev/fd0 footer.txt >& 4 cat result.txt 4をresult.txt(出力用)に。file4にcat結果をinput.このoutputがresut.txt. result.txtをcat |
cat sysnotes.sh #!/bin/bash # This script makes an index of important config files, puts them together in # a backup file and allows for adding comment for each file. CONFIG=/var/tmp/sysconfig.out rm "$CONFIG" 2>/dev/null echo "Output will be saved in $CONFIG." # create fd 7 with same target as fd 0 (save stdin "value"):7を標準入力と同じに exec 7<&0 # update fd 0 to target file /etc/passwd:標準入力を/etc/passwd exec < /etc/passwd # Read the first line of /etc/passwd read rootpasswd echo "Saving root account info..." echo "Your root account info:" >> "$CONFIG" echo $rootpasswd >> "$CONFIG" # update fd 0 to target fd 7 target (old fd 0 target); delete fd 7:標準入力を7(以前の標準入力) exec 0<&7 7<&- echo -n "Enter comment or [ENTER] for no comment: " read comment; echo $comment >> "$CONFIG" echo "Saving hosts information..." # first prepare a hosts file not containing any comments TEMP="/var/tmp/hosts.tmp" cat /etc/hosts | grep -v "^#" > "$TEMP" exec 7<&0 exec < "$TEMP" read ip1 name1 alias1 read ip2 name2 alias2 echo "Your local host configuration:" >> "$CONFIG" echo "$ip1 $name1 $alias1" >> "$CONFIG" echo "$ip2 $name2 $alias2" >> "$CONFIG" exec 0<&7 7<&- echo -n "Enter comment or [ENTER] for no comment: " read comment; echo $comment >> "$CONFIG" rm "$TEMP" ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー michel ~/testdir> sysnotes.sh Output will be saved in /var/tmp/sysconfig.out. Saving root account info... Enter comment or [ENTER] for no comment: hint for password: blue lagoon Saving hosts information... Enter comment or [ENTER] for no comment: in central DNS michel ~/testdir> cat /var/tmp/sysconfig.out Your root account info: root:x:0:0:root:/root:/bin/bash hint for password: blue lagoon Your local host configuration: 127.0.0.1 localhost.localdomain localhost 192.168.42.1 tintagel.kingarthur.com tintagel in central DNS |
michel ~> cat listdirs.sh
#!/bin/bash
# This script prints standard output unchanged, while standard error is
# redirected for processing by awk.
INPUTDIR="$1"
# fd 6 targets fd 1 target (console out) in current shell(6を標準出力に)
exec 6>&1
# fd 1 targets pipe, fd 2 targets fd 1 target (pipe),(1をパイプに、2を1の標的に(パイプ)
# fd 1 targets fd 6 target (console out), fd 6 closed, execute ls(1を6の標的に(画面)、6閉じlsを実行)
ls "$INPUTDIR"/* 2>&1 >&6 6>&- \
# Closes fd 6 for awk, but not for ls.
| awk 'BEGIN { FS=":" } { print "YOU HAVE NO ACCESS TO" $2 }' 6>&-
# fd 6 closed for current shell
exec 6>&-
#!/bin/bash # This script provides an easy way for users to choose between browsers echo "These are the web browsers on this system." # Start here document cat << BROWSERS mozilla links Konquaror lynx opera netscape BROWSERS # End here document echo -n "Which is your favorite?" read browser echo "Starting $browser, please wait..." $browser & michel ~> startsurf.sh |
cat installs.sh #!/bin/bash # This script installs packages autimacally using yum if [$# -lt 1] ; then echo "Usage: $0 package" exit 1 fi yum install $1 << CONFIRM y CONFIRM |
carol@octarine ~/articles] ls *.xml |
for i in `ls /sbin`; do file /sbin/$i | grep ASCII; done ..sbin中のテキストファイルをリスト(多分スクリプト)
htmi -> phpにあたって |
#!/bin/bash # This script opens 4 terminal windows. i="0" while [$i -lt 4] do xterm & i=$[$i+1] done |
cat webcamcopy.sh #!/bin/bash # This script copies files from my home directory into the webserver directory # (use scp and ssh keys for a remote directory) # A new directory is created every hour. PICTDIR=/home/ouryouji/pics WEBDIR=/var/www/ouryouji/webcam while true; do DATE=`date +%Y%m%d` HOUR=`date +%H` mkdir $WEBDIR/"$DATE" while [$HOUR -ne "00"] ; do DESTDIR=$WEBDIR/"$DATE"/"$HOUR" mkdir "$DESTDIR" mv $PICTDIR/*.jpeg "$DESTDIR"/ sleep 3600 HOUR=`date +%H` done done true statement は強制終了されるまで実行しつづけることを意味する これはsimulation testing用(ファイル生成) |
#!/bin/bash # This script provides wisdom FORTUNE=/usr/games/fortune while true ; do echo "On which topic do you want advice?" cat << topics politics startreck kernelnewbies sports bofh-excuses magic love literature drugs education topics echo echo "Free advice on the topic of $topics:" echo $FORTUNE $topic echo done here documentが選択に使われtrue testがconsequent command listを繰り返す。 |
#!/bin/bash # Calculate the average of a series of numbers SCORE="0" AVERATGE="0" SUM="0" NUM="0" while true ; do echo -n "Enter your score [0-100%]('q' for quit):"; read SCORE; if (("$SCORE" < "0")) || (("$SCORE" > "100" )) ; then echo "Be serious . Common, try again elif [$SCORE" == "q"] ; then echo "Average rating; $AVERAGE%." break else SUM=$[$SUM + $SCORE] NUM=$ [$NUM + 1] AVERAGE = $ [ $SUM / $NUM] fi done echo "Exiting" 最後の行の変数は算術のためにクォートしてない事に注意 |
#!/bin/bash |
#!/bin/bash # This script creates a subdirectory in the current directory, # to which old files are moved. # might be something for cron (if slightly adapted) to execute # weekly or monthly ARCHIVER=`date +%Y%m%d` DESTDIR="$PWD/archive-$ARCHIVER" mkdir "$DESTDIR" # using quotes to catch file names containing spaces,using read -d for more # fool-proof usage find $PWD -type f -a -mtime +5 | while read -d $'\000' file #デリミタがこれというのが分からない do gzip "$file" ; mv "$file.gz" "$DESTDIR" echo "file archived" done |
#!/bin/bash # This script provides a wisdom # You can now exit in a descent way FORTUNE=/usr/games/fortune while true ; do echo "On which topic do you want to advice? echo "1.politics echo "2. startrek" echo "3. kernelnewbies" echo "4. sports" echo "5. bofh-excusec" echo "6. magic" echo "7. love" echo "8. literature" echo "9. drugs" echo "10. education" echo echo -n "Enter your choice, or 0 for exit" read choice echo case $choice in 1) $ FORTUNE politics ;; 2) $FORTUNE srartrek ;; 3) $FORTUNE kernelnewbies ;; 4) echo "Sports are a waste of time, energy and money." echo "Go back to your keyword." echo -e "\t\t\t...\"Unhealthy is my middle name\"Soggie" ;; 5) $FORTUNE bufh-excuses ;; 6) $FORTUNE magic ;; 7) $FORTUNE love ;; 8) $FORTUNE literature ;; 9) $FORTUNE drugs ;; 10) $FORTUNE education ;; 0) echo "OK. see you!" break # exit the loop not the script ;; *) echo "That is not a valid choice, try a number from 0 to 10." ;; esac done |
#!/bin/bash # This script converts all file names containing upper case characters into file# names containing only lower cases LIST="$(ls)" for name in "LIST" ; do if [["$name"!=*[[:upper:]]*]]; then continue fi ORIG="$name" NEW=`echo $name | tr 'A-Z' 'a-z'` mv "$ORIG" "NEW" echo "new name for $ORIG is $NEW" done |
private.sh #!/bin/bash echo "This script can make any of the file in this directory private." echo "Enter the number of the file you want to protect:" select FILENAME in *; do echo "You picked $ FILENAME($REPLY), it is now only accessible to you." chmod go-rwx "$FILENAME" done |
#!/bin/bash |
cleanup.sh #!/bin/bash # This script can clean up files that were last accessed over 365 days ago USAGE="Usage: $0 dir1 dir2 dir3... dirN" if [ "$#" == "0" ] ; then echo "$USAGE" exit 1 fi while (( "$#" )); do if [[ $(ls "$1" )) == ""]] ; then echo "Empty directory, nothing to be done." else find "$1" -type f -a -atime +365 -exec rm -i {} \; fi shift done |
[bob in ~] declare -i VARIABLE=12
[bob in ~] VARIABLE=string
[bob in ~] echo $VARIABLE
0
[bob in ~] declare -p VARIABLE
declare -i VARIABLE="0"