$ echo '#!/bin/sh' > my-script.sh
$ echo 'echo Hello World' >> my-script.sh
$ chmod 755 my-script.sh
$ ./my-script.sh
Hello World
$
上面這段代碼中,echo
是打印的意思,而>
是重定向的意思,chmod
是修改權限的意思。shell
腳本以.sh
為結尾。
#!/bin/sh
# This is a comment!
echo Hello World # This is a comment, too!
以上為my-script.sh
中的代碼,可以學習一下如何寫注釋。
$ chmod a+rx my-script.sh
$ ./my-script.sh
想要將shell
腳本變成可執行的,可以使用以上語句。
grep "mystring" /tmp/myfile
這句的意思是將在/tmp/myfile
中的"mystring"
字符串搜索出來。
#!/bin/sh
# This is a comment!
echo Hello World # This is a comment, too!
以上是first.sh
中的代碼。可以使用以下代碼執行:
$ chmod 755 first.sh
$ ./first.sh
Hello World
$
得到結果:
$ echo Hello World
Hello World
$
#!/bin/sh
MY_MESSAGE="Hello World"
echo $MY_MESSAGE
以上是var.sh
的代碼。用來學習變量的使用。環境變量使用以下代碼實現:
$ export name=zuoyuan
#!/bin/sh
echo What is your name?
read MY_NAME
echo "Hello $MY_NAME - hope you're well."
以上是var2.sh
的代碼。
#!/bin/sh
echo "What is your name?"
read USER_NAME
echo "Hello $USER_NAME"
echo "I will create you a file called ${USER_NAME}_file"
touch "${USER_NAME}_file"
以上代碼可以創建一個文件,touch
關鍵字的作用是如果有這個文件,不做任何操作,如果沒有這個文件,就創建一個這個文件。
#!/bin/sh
for i in 1 2 3 4 5
do
echo "Looping ... number $i"
done
以上是for
循環。寫入for.sh
。
#!/bin/sh
for i in hello 1 * 2 goodbye
do
echo "Looping ... i is set to $i"
done
繼續for
循環。寫入for2.sh
中。
#!/bin/sh
INPUT_STRING=hello
while [ "$INPUT_STRING" != "bye" ]
do
echo "Please type something in (bye to quit)"
read INPUT_STRING
echo "You typed: $INPUT_STRING"
done
while
循環。
#!/bin/sh
while :
do
echo "Please type something in (^C to quit)"
read INPUT_STRING
echo "You typed: $INPUT_STRING"
done
繼續while
循環。
#!/bin/sh
while read f
do
case $f in
hello) echo English ;;
howdy) echo American ;;
gday) echo Australian ;;
bonjour) echo French ;;
"guten tag") echo German ;;
*) echo Unknown Language: $f
;;
esac
done < myfile
使用while
循環讀取文件。
for runlevel in 0 1 2 3 4 5 6 S
do
mkdir rc${runlevel}.d
done
批量建文件。
if [ ... ]
then
# if-code
else
# else-code
fi
if [ ... ]; then
# do something
fi
if [ something ]; then
echo "Something"
elif [ something_else ]; then
echo "Something else"
else
echo "None of the above"
fi
以上是幾種條件結構。
#!/bin/sh
if [ "$X" -lt "0" ]
then
echo "X is less than zero"
fi
if [ "$X" -gt "0" ]; then
echo "X is more than zero"
fi
[ "$X" -le "0" ] && \
echo "X is less than or equal to zero"
[ "$X" -ge "0" ] && \
echo "X is more than or equal to zero"
[ "$X" = "0" ] && \
echo "X is the string or number \"0\""
[ "$X" = "hello" ] && \
echo "X matches the string \"hello\""
[ "$X" != "hello" ] && \
echo "X is not the string \"hello\""
[ -n "$X" ] && \
echo "X is of nonzero length"
[ -f "$X" ] && \
echo "X is the path of a real file" || \
echo "No such file: $X"
[ -x "$X" ] && \
echo "X is the path of an executable file"
[ "$X" -nt "/etc/passwd" ] && \
echo "X is a file which is newer than /etc/passwd"
echo -en "Please guess the magic number: "
read X
echo $X | grep "[^0-9]" > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
# If the grep found something other than 0-9
# then it's not an integer.
echo "Sorry, wanted a number"
else
# The grep found only 0-9, so it's an integer.
# We can safely do a test on it.
if [ "$X" -eq "7" ]; then
echo "You entered the magic number!"
fi
fi
#!/bin/sh
X=0
while [ -n "$X" ]
do
echo "Enter some text (RETURN to quit)"
read X
echo "You said: $X"
done
#!/bin/sh
X=0
while [ -n "$X" ]
do
echo "Enter some text (RETURN to quit)"
read X
if [ -n "$X" ]; then
echo "You said: $X"
fi
done
if [ "$X" -lt "0" ]
then
echo "X is less than zero"
fi
.......... and ........
if [ ! -n "$X" ]; then
echo "You said: $X"
fi
以上是幾個條件結構的例子。
繼續舉幾個例子。
#!/bin/sh
echo "Please talk to me ..."
while :
do
read INPUT_STRING
case $INPUT_STRING in
hello)
echo "Hello yourself!"
;;
bye)
echo "See you again!"
break
;;
*)
echo "Sorry, I don't understand"
;;
esac
done
echo
echo "That's all folks!"
運行后有以下結果。
$ ./talk.sh
Please talk to me ...
hello
Hello yourself!
What do you think of politics?
Sorry, I don't understand
bye
See you again!
That's all folks!
$
繼續學習變量。以下代碼寫入var3.sh
。
#!/bin/sh
echo "I was called with $# parameters"
echo "My name is $0"
echo "My first parameter is $1"
echo "My second parameter is $2"
echo "All parameters are $@"
運行結果如下:
$ /home/steve/var3.sh
I was called with 0 parameters
My name is /home/steve/var3.sh
My first parameter is
My second parameter is
All parameters are
$
$ ./var3.sh hello world earth
I was called with 3 parameters
My name is ./var3.sh
My first parameter is hello
My second parameter is world
All parameters are hello world earth
繼續學習變量。以下代碼寫入var4.sh
。
#!/bin/sh
while [ "$#" -gt "0" ]
do
echo "\$1 is $1"
shift
done
This script keeps on using shift
until $#
is down to zero, at which point the list is empty.
Another special variable is $?
. This contains the exit value of the last run command. So the code:
#!/bin/sh
/usr/local/bin/my-command
if [ "$?" -ne "0" ]; then
echo "Sorry, we had a problem there!"
fi
當進程退出時的代碼為0
時,就沒有問題。
#!/bin/sh
old_IFS="$IFS"
IFS=:
echo "Please input some data separated by colons ..."
read x y z
IFS=$old_IFS
echo "x is $x y is $y z is $z"
寫入var5.sh
。運行如下:
$ ./ifs.sh
Please input some data separated by colons ...
hello:how are you:today
x is hello y is how are you z is today
$ ./ifs.sh
Please input some data separated by colons ...
hello:how are you:today:my:friend
x is hello y is how are you z is today:my:friend
使用默認變量。
#!/bin/sh
echo -en "What is your name [ `whoami` ] "
read myname
if [ -z "$myname" ]; then
myname=`whoami`
fi
echo "Your name is : $myname"
函數的用法。
#!/bin/sh
# A simple script with a function...
add_a_user()
{
USER=$1
PASSWORD=$2
shift; shift;
# Having shifted twice, the rest is now comments ...
COMMENTS=$@
echo "Adding user $USER ..."
echo useradd -c "$COMMENTS" $USER
echo passwd $USER $PASSWORD
echo "Added user $USER ($COMMENTS) with pass $PASSWORD"
}
###
# Main body of script starts here
###
echo "Start of script..."
add_a_user bob letmein Bob Holness the presenter
add_a_user fred badpassword Fred Durst the singer
add_a_user bilko worsepassword Sgt. Bilko the role model
echo "End of script..."
階乘的shell實現,使用遞歸。
#!/bin/sh
factorial()
{
if [ "$1" -gt "1" ]; then
i=`expr $1 - 1`
j=`factorial $i`
k=`expr $1 \* $j`
echo $k
else
echo 1
fi
}
while :
do
echo "Enter a number:"
read x
factorial $x
done
模塊化編程。以下代碼寫入common.lib
。
# common.lib
# Note no #!/bin/sh as this should not spawn
# an extra shell. It's not the end of the world
# to have one, but clearer not to.
#
STD_MSG="About to rename some files..."
rename()
{
# expects to be called as: rename .txt .bak
FROM=$1
TO=$2
for i in *$FROM
do
j=`basename $i $FROM`
mv $i ${j}$TO
done
}
以下代碼寫入function2.sh
。
#!/bin/sh
# function2.sh
. ./common.lib
echo $STD_MSG
rename .txt .bak
返回碼。
#!/bin/sh
adduser()
{
USER=$1
PASSWORD=$2
shift ; shift
COMMENTS=$@
useradd -c "${COMMENTS}" $USER
if [ "$?" -ne "0" ]; then
echo "Useradd failed"
return 1
fi
passwd $USER $PASSWORD
if [ "$?" -ne "0" ]; then
echo "Setting password failed"
return 2
fi
echo "Added user $USER ($COMMENTS) with pass $PASSWORD"
}
## Main script starts here
adduser bob letmein Bob Holness from Blockbusters
ADDUSER_RETURN_CODE=$?
if [ "$ADDUSER_RETURN_CODE" -eq "1" ]; then
echo "Something went wrong with useradd"
elif [ "$ADDUSER_RETURN_CODE" -eq "2" ]; then
echo "Something went wrong with passwd"
else
echo "Bob Holness added to the system."
fi
crontab的使用
在考慮向cron進程提交一個crontab文件之前,首先要做的一件事情就是設置環境變量EDITOR。cron進程根據它來確定使用哪個編輯器編輯crontab文件。9 9 %的UNIX和LINUX用戶都使用vi,如果你也是這樣,那么你就編輯$ HOME目錄下的. profile文件,在其中加入這樣一行:
EDITOR=vi; export EDITOR
然后保存并退出。不妨創建一個名為<user>cron
的文件,其中<user>
是用戶名,例如,davecron
。在該文件中加入如下的內容。
# (put your own initials here)echo the date to the console every
# 15minutes between 6pm and 6am
0,15,30,45 18-06 * * * /bin/echo 'date' > /dev/console
保存并退出。確信前面5個域用空格分隔。
在上面的例子中,系統將每隔1 5分鐘向控制臺輸出一次當前時間。如果系統崩潰或掛起,從最后所顯示的時間就可以一眼看出系統是什么時間停止工作的。在有些系統中,用tty1來表示控制臺,可以根據實際情況對上面的例子進行相應的修改。為了提交你剛剛創建的crontab文件,可以把這個新創建的文件作為cron
命令的參數:
$ crontab davecron
現在該文件已經提交給cron進程,它將每隔15分鐘運行一次。
同時,新創建文件的一個副本已經被放在/var/spool/cron目錄中,文件名就是用戶名(即dave)。
為了列出crontab文件,可以用:
$ crontab -l